Page 67 - Python rat la co ban
P. 67
...
db = MySQLdb.connect(host = 'localhost', user = 'ro
ot', passwd = 'root', db = 'test', charset = 'utf8'
)
9.4. Query dữ liệu
Để truy vấn dữ liệu (chạy câu lệnh SQL) thì sử dụng cursor
của MySQLdb. Ví dụ:
import MySQLdb
db = MySQLdb.connect(host = 'localhost', user = 'ro
ot', passwd = 'root', db = 'mysql');
cursor = db.cursor()
sql = 'SELECT * FROM user'
cursor.execute(sql)
myusers = cursor.fetchall()
Ví dụ dữ liệu biến myusers là: ((1, 'John'), (2, 'Doe'))
Mặc định, cursor sẽ trả về mỗi dòng dữ liệu từ MySQL
theo kiểu tuple , tức là không có key. Nếu bạn muốn trả về