先来一个简单的例子
注意charset = 'utf8‘一句
如果你的sql中采用的是utf8编码并且数据库内容里边有中文的话一定要加上这句,不然容易乱码
import MySQLdb
try:
conn = MySQLdb.connect(host = 'localhost', user = 'root',
passwd = 'fx',db = 'test', charset = 'utf8')
cur = conn.cursor()
cur.execute('select * from usrlogin')
for date in cur.fetchall():
print date
cur.close()
conn.close()
except MySQLdb.Error, e:
print "mysql error %d:%s" %(e.args[0], e.args[1])
插入数据, 批量插入数据, 更改数据
import MySQLdb
try:
conn = MySQLdb.connect(host = 'localhost', user = 'root',
passwd = 'fx')
cur = conn.cursor()
cur.execute('create database if not exists python')
conn.select_db('python')
cur.execute('create table test(id int, info varchar(20))')
value = []
for i in range(20):
value.append((i, 'hi rollen' + str(i)))
cur.executemany('insert into test values(%s, %s)', value)
cur.execute('update test set info = "I am rollen" where id = 3')
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error, e:
print "mysql error %d %s" % (e.args[0], e.args[1])
注意要用 conn.commit()提交事务,不然不会真正把数据插进去
下面贴一下常用的函数:
然后,这个连接对象也提供了对事务操作的支持,标准的方法
commit() 提交
rollback() 回滚
cursor用来执行命令的方法:
callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self):移动到下一个结果集
cursor用来接收返回值的方法:
fetchall(self):接收全部的返回结果行.
fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):返回一条结果行.
scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.