【www.bbyears.com--python】
之前一直用torndb和SQLAlchemy,这次自己关注了下MySQLdb,感觉如果对T-SQL比较了解的下,还是用MySQLdb更灵活,而且很简单,不是吗?它所有的操作就只用一个execute()方法。
代码如下# -*- coding: utf-8 -*-
import MySQLdb
conn = MySQLdb.connect(host="localhost",db="mydata", user="root", passwd="root", charset="utf8")
cursor = conn.cursor()
#添加数据,其他修改、删除操作也是如下操作
sql = "INSERT INTO authors(email, name) VALUES(%s, %s)"
param = ("hello@17python.com", "17python")
n = cursor.execute(sql, param)
print n
#查询数据
sql = "SELECT email,name FROM authors"
cursor.execute(sql)
for row in cursor.fetchall():
print "email: %s - name: %s" % (row[0], row[1])
cursor.close()
conn.commit() #提交事物,一定要记到
conn.close()