我想給Python變數加上從MySQL資料庫獲取的值。
#!/usr/bin/python -u
# -*- 編碼。UTF-8 -*-
import time
import datetime
import mysql.connector
import sys
db = mysql.connector.connect(
host = "localhost"。
user = "admin",
password = "admin",
db = "testonly", db = "testonly".
)
mycursor = db.cursor()
if __name__ == '__main__':
temp = 0.
mycursor.execute("SELECT temperature FROM table ORDER BY primarykey DESC LIMIT 1;"/span>) #通過選擇一行中的一列,我只從talbe中獲取一條記錄。
data = mycursor.fetchone()
for temperature in data:
print(temperature)
temp = data['temperature']
sys.exit()
然后我的錯誤是:
檔案 "test.py", 第28行, in <module>
temp = data['temperature']
TypeError: 元組索引必須是整數,而不是str
我可以通過哪種方式給Python變數賦值供以后使用呢?
uj5u.com熱心網友回復:
默認情況下,fetchone回傳一個帶有資料庫資料的元組。就目前而言,你需要通過索引來訪問你的資料
temp = data[0]
如果你想通過temperature鍵訪問你的資料,你需要使用指定你的游標
from mysql.connector.cursor import MySQLCursorDict
...
mycursor = db.cursor(cursor_class=MySQLCursorDict)
...
temp = data['temperature']
uj5u.com熱心網友回復:
你的物件data是一個元組,不能像這樣被參考。你需要使用這個:
temp = data[0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/306799.html
標籤:
