Skip to content

Commit a4a10d4

Browse files
committed
Python Databases Tutorial - MySQL
1 parent 02da423 commit a4a10d4

File tree

1 file changed

+144
-0
lines changed

1 file changed

+144
-0
lines changed
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
# Python Databases Tutorial - MySQL
2+
3+
4+
### install and setting
5+
```
6+
sudo apt-get install mysql-server
7+
sudo apt-get install python-mysqldb
8+
mysql -u root -p
9+
# create a user and table in mysql
10+
> CREATE DATABASE testdb;
11+
> CREATE USER 'testuser'@'localhost' IDENTIFIED BY '123';
12+
> USE testdb;
13+
> GRANT ALL ON testdb.* TO 'testuser'@'localhost';
14+
```
15+
16+
17+
### _mysql module
18+
19+
The _mysql module implements the MySQL C API directly.
20+
Not compatible.
21+
22+
Fetch version
23+
24+
```
25+
#!/usr/bin/python
26+
# -*- coding: utf-8 -*-
27+
28+
import _mysql
29+
import sys
30+
31+
try:
32+
con = _mysql.connect('localhost', 'test', '123', 'testdb')
33+
34+
con.query("SELECT VERSION()")
35+
result = con.use_result()
36+
37+
print "MySQL version: %s" % \
38+
result.fetch_row()[0]
39+
40+
except _mysql.Error, e:
41+
42+
print "Error %d: %s" % (e.args[0], e.args[1])
43+
sys.exit(1)
44+
45+
finally:
46+
if con:
47+
con.close()
48+
```
49+
50+
51+
### MySQLdb module
52+
53+
MySQLdb is a thin Python wrapper around _mysql.
54+
55+
56+
1. con = mdb.connect(...)
57+
2. cur = con.cursor() // **get cursor**
58+
3. cur.execute("SELECT * FROM xxx")
59+
4. cur.executemany("INSERT INTO xxx VALUES(%s, %s)", value_list)
60+
4. except mdb.Error, e // **remember this**
61+
5. cur.rowcount
62+
6. cur.fetchone() // **return one**
63+
7. cur.fetchall() // **return a list**
64+
8. cur = con.cursor(mdb.cursors.DictCursor) // **dictionary cursor, we can refer to the data by their column names**
65+
9. desc = cur.description // **table column names**
66+
67+
68+
Fetch version.
69+
70+
```
71+
#!/usr/bin/python
72+
# -*- coding: utf-8 -*-
73+
74+
import MySQLdb as mdb
75+
import sys
76+
77+
try:
78+
con = mdb.connect('localhost', 'test', '123', 'testdb');
79+
cur = con.cursor()
80+
cur.execute("SELECT VERSION()")
81+
82+
ver = cur.fetchone()
83+
print "Database version : %s " % ver
84+
85+
except mdb.Error, e:
86+
print "Error %d: %s" % (e.args[0],e.args[1])
87+
sys.exit(1)
88+
89+
finally:
90+
if con:
91+
con.close()
92+
```
93+
94+
Create a table and populate it with some data
95+
96+
```
97+
#!/usr/bin/python
98+
# -*- coding: utf-8 -*-
99+
100+
import MySQLdb as mdb
101+
102+
con = mdb.connect('localhost', 'test', '123', 'testdb');
103+
104+
with con: # automatically release con
105+
cur = con.cursor()
106+
# Above can be `with mdb.connect(...) as cur`
107+
108+
cur.execute("DROP TABLE IF EXISTS Writers")
109+
cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \
110+
Name VARCHAR(25))")
111+
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
112+
```
113+
114+
Retrieving data
115+
116+
```
117+
#!/usr/bin/python
118+
# -*- coding: utf-8 -*-
119+
120+
import MySQLdb as mdb
121+
122+
con = mdb.connect('localhost', 'test', '123', 'testdb');
123+
124+
with con:
125+
cur = con.cursor() # con.cursor(mdb.cursors.DictCursor)
126+
cur.execute("SELECT * FROM Writers")
127+
128+
rows = cur.fetchall() # if is DictCursor rows is a dict
129+
for row in rows:
130+
print row
131+
132+
# or fetch one by one
133+
# for i in range(cur.rowcount):
134+
# row = cur.fetchone()
135+
# print row
136+
```
137+
138+
139+
### Some resources:
140+
[MySQLdb User's Guide](http://mysql-python.sourceforge.net/MySQLdb.html)
141+
[python-mysqldb API](http://mysql-python.sourceforge.net/MySQLdb-1.2.2/)
142+
[StackOverflow-How do I connect to a MySQL Database in Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python)
143+
[Good start:Zencode](http://zetcode.com/db/mysqlpython/) (I use this :smile:)
144+

0 commit comments

Comments
 (0)