- 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
獲取一條記錄,每條記錄做為一個(gè)元組返回
print "只獲取一條記錄:"
result = cursor.fetchone();
print result
print 'ID: %s info: %s' % (result[0],result[1])
print 'ID: %s info: %s' % result
獲取5條記錄,注意由于之前執(zhí)行有了fetchone()融柬,所以游標(biāo)已經(jīng)指到第二條記錄了,也就是從第二條開始的所有記錄
print "只獲取5條記錄:"
results = cursor.fetchmany(5)
for r in results:
print r
print "獲取所有結(jié)果:"
重置游標(biāo)位置,0,為偏移量,mode=absolute | relative,默認(rèn)為relative,
cursor.scroll(0,mode='absolute')
獲取所有結(jié)果
results = cursor.fetchall()
for r in results:
print r
conn.close()
`
- 解決返回的元組問題
`默認(rèn)mysqldb返回的是元組,這樣對(duì)使用者不太友好,也不利于維護(hù)
**下面是解決方法
**
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
`