Python下MySQLdb库的使用

Python下MySQLdb库的项目地址是:http://sourceforge.net/projects/mysql-python/

连接:

conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")
cursor = conn.cursor()

写入:

sql = "insert into user(name,created) values(%s,%s)"
param = ("aaa",int(time.time()))
n = cursor.execute(sql,param)
conn.commit()
print n

注:executemany 的param可以传入一个序列,批量执行

更新:

sql = "update user set name=%s where id=3"
param = ("bbb")
n = cursor.execute(sql,param)
print n

查询:

n = cursor.execute("select * from user")
for row in cursor.fetchall():
for r in row:
	print r

删除:

sql = "delete from user where name=%s"
param =("aaa")
n = cursor.execute(sql,param)
print n

关闭:

cursor.close()
conn.close()

发表评论

电子邮件地址不会被公开。 必填项已用*标注