使用MySQLdb连接Mysql,并进行一些常见操作:
import time
import MySQLdb
#连接Mysql
conn = MySQLdb.connect(host="localhost",port=3306,user="root",passwd="",db="test",charset="utf8")
#无需conn.commit()来手动提交修改
conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8", autocommit=True)
#连接本地sock文件
conn = MySQLdb.connect(unix_socket="/xxx/mysqld.sock",user="root",passwd="",db="test",charset="utf8")
cursor = conn.cursor()
#写入
conn.ping(True) #如果发现断开就重连
sql = "insert into user(name,created) values(%s,%s)"
param = ("aaa",int(time.time()))
n = cursor.execute(sql,param)
conn.commit() #需要手动提交
print(n)
#更新
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()
向Mysql中存储二进制文件(比如图片)的例子代码:
conn = MySQLdb.connect(host='localhost',user='root',passwd='root', db='test')
cursor = conn.cursor()
#直接将数据作为字符串,插入数据库
cursor.execute("INSERT INTO Images SET Data='%s'" % MySQLdb.escape_string(file(img_file).read()))
#提交数据
conn.commit()
#提交之后,再关闭cursor和链接
cursor.close()
conn.close()
常见问题1:与MySQL的连接丢失问题
需要使用ping()来重新建议连接,可以这样写:
conn.ping(True)
n = cursor.execute("select data from Image where sign='%s'" % sign)
for row in cursor.fetchall():
with open(sign, 'w') as f:
f.write(row[0])
如果还是会出现,就更暴力一点,这样写:
while True:
try:
n = cursor.execute("select data from Image where sign='%s'" % sign)
for row in cursor.fetchall():
with open(sign, 'w') as f:
f.write(row[0])
break
except:
conn.ping(True)
常见问题2:获取insert产生的自增ID
需要在执行SQL语句后立马获取cursor.lastrowid的值,千万不能在commit()之后。发现一个有趣的现象,假如在ipython中一步一步执行下面代码,当执行execute()后,主键ID已经在该连接中确定了,如果此时手动登录数据库再插入另外一条数据,会发现新插入数据跳过了此主键ID,但是却查询不到ipython中插入的数据。而当执行commit()之后,数据才能被查询到。
conn.ping(True)
cursor.execute("INSERT INTO Student (`name`,`age`) VALUES (%s,%s)", ('wangyang', 100))
lastid = cursor.lastrowid
conn.commit()
常见问题3:批量输入executemany()使用
可以拼sql,也可以使用executemany()方法来实现,例子如下:
c.executemany("INSERT INTO breakfast (name,spam,eggs,sausage,price) VALUES (%s,%s,%s,%s,%s)",
[
("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95),
("Not So Much Spam Plate", 3, 2, 0, 3.95),
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95)
])
使用execute()和executemany()的第二个参数,MySQLdb会根据类型自动转义和加引号,这种使用只适合于where条件中的value,insert中的value。