我正在嘗試使用MySQL表來存儲報表定義的屬性。由於每個報告使用不同的屬性,我想要存儲三列 - report_name,attribute,attribute_value。python - 如何創建變量並從數據表中設置其值
我想查詢表的report_name並獲取相關的屬性和attribute_values。我已經在其他問題看出,人們可以使用
exec("%s = %s" % (row[0], (row[1],)))
動態設置變量的名稱(行[0]是屬性,行[1]是ATTRIBUTE_VALUE)。我的問題是,結果是變量是元組。
title_text = ('Daily PnL',)
title_text是屬性。 '每日PnL'是attribute_value。
我不能簡單地說
exec("%s = %s" % (row[0], row[1]))
我得到的錯誤是:
Traceback (most recent call last):
File "C:\...\test_dynamic_variables.py", line 17, in <module>
exec("%s = %s" % (row[0], row[1]))
File "<string>", line 1, in <module>
NameError: name 'Daily PnL' is not defined
這裏是更大的一組代碼:
import mysql.connector
from mysql.connector import errorcode
cnx = mysql.connector.connect(user='xxxx', password='xxxx', database='xxxx')
cursor = cnx.cursor()
query = ("SELECT attribute, attribute_value FROM reports WHERE report_name = %s")
report_name = 'Daily'
try:
cursor.execute(query, (report_name,))
except mysql.connector.Error as err:
print(err.msg)
row = cursor.fetchone()
while row is not None:
exec("%s = %s" % (row[0], row[1]))
row = cursor.fetchone()
print(title_text) #test if works
感謝您幫幫我。
ok。只是想出瞭如何正確格式化。抱歉的混淆。 – Andrew