- Author: 杜七
- Date:2016.05.19
MySQLdb
- 基本的使用
`
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')
cursor = conn.cursor()
count = cursor.execute('select * from test')
print '总共有 %s 条记录',count
获取一条记录,每条记录做为一个元组返回
print "只获取一条记录:"
result = cursor.fetchone();
print result
print 'ID: %s info: %s' % (result[0],result[1])
print 'ID: %s info: %s' % result
获取5条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录
print "只获取5条记录:"
results = cursor.fetchmany(5)
for r in results:
print r
print "获取所有结果:"
重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,
cursor.scroll(0,mode='absolute')
获取所有结果
results = cursor.fetchall()
for r in results:
print r
conn.close()
`
- 解决返回的元组问题
`默认mysqldb返回的是元组,这样对使用者不太友好,也不利于维护
**下面是解决方法
**
import MySQLdb
import MySQLdb.cursors
conn = MySQLdb.Connect (
host = 'localhost', user = 'root' ,
passwd = '', db = 'test', compress = 1,
cursorclass = MySQLdb.cursors.DictCursor, charset='utf8')
// <- important
cursor = conn.cursor()
cursor.execute ("SELECT name, txt FROM table")
rows = cursor.fetchall()
cursor.close()
conn.close()
for row in rows:
print row ['name'], row ['txt'] # bingo!
another (even better) way is:
conn = MySQLdb . Connect (
host = ' localhost ', user = 'root' ,
passwd = '', db = 'test' , compress = 1)
cursor = conn.cursor (cursorclass = MySQLdb.cursors.DictCursor)
...
results by field name
cursor = conn.cursor()
...
...results by field number
`