Python的MySQLdb模塊是Python連接MySQL的一個模塊,默認查詢結果返回是tuple類型,只能通過0,1..等索引下標訪問數據
默認連接數據庫:
代碼如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset='utf8'
)
查詢數據:
代碼如下:
cur = conn.cursor()
cur.execute('select b_id from blog limit 1')
data = cur.fetchall()
cur.close()
conn.close()
打印:
代碼如下:
for row in data:
print type(row)
print row
執行結果:
代碼如下:
<type 'tuple'>
(1L,)
為tuple類型。
我們可以這么干使得數據查詢結果返回字典類型,即 字段=數據
導入模塊
代碼如下:
import MySQLdb.cursors
在連接函數里加上這個參數 cursorclass = MySQLdb.cursors.DictCursor 如:
代碼如下:
MySQLdb.connect(
host=host,
user=user,
passwd=passwd,
db=db,
port=port,
charset='utf8',
cursorclass = MySQLdb.cursors.DictCursor
)
再重新運行腳本,看看執行結果:
代碼如下:
<type 'dict'>
{'b_id': 1L}
搞定!
注意,在連接的時候port如果要指定則值必須是整型,否則會出錯!
新聞熱點
疑難解答