1.MySQLdb模块的介绍
MySQLdb is a Python DB API-2.0-compliant interface; seePEP-249 for details.
2.使用
导入模块:
import MySQLdb
数据库连接:
conn = MySQLdb.connect(host='localhost',user='root',passwd='admin',db='test')
获取游标对象:
cursor = conn.cursor()
sql = "insert into test(name, age) values ('%s', %d)" % ("张三", 21)
cursor.execute(sql)
一次性插入多条记录executemany()函数:
sql = "insert into test(name, age) values (%s, %s)"
val = (("li", 24), ("wang", 25), ("limig", 26))
cursor.executemany(sql, val)
数据查询:
sql = "select * from test"
cursor.execute(sql)
data = cursor.fetchall()
if data:
for rec in data:
print rec[0], rec[1]
cursor.close()
最后要记住不要忘记关闭连接:
conn.close()
简单的例子:
import MySQLdb
if __name__ == '__main__':
conn = MySQLdb.connect(db='test',user='root',passwd='admin')
cursor = conn.cursor()
sql = "select * from movies"
cursor.execute(sql)
data = cursor.fetchall()
print len(data)
if data:
for row in data:
print str(row[0])+row[1]+row[2]