我收到以下错误:
File "pymon.py", line 18
sql += "'" + str(gpu['GPU Clock'] + "', "
^
如果有帮助,这是代码的一部分:
def parsedata(data, ngpu):
for gpu in data:
sql = "UPDATE pythondb SET (minerid, temp, load, hashrate, accepted, rejected, coreclock, memclock, power, hwerror) VALUES "
sql += "("
sql += "'" + str(gpu['Temperature']) + "', "
sql += "'" + str(gpu['GPU Activity']) + "', "
sql += "'" + str(gpu['MHS av'] * 1000) + "', "
sql += "'" + str(gpu['Accepted']) + "', "
sql += "'" + str(gpu['Rejected'] + "', "
sql += "'" + str(gpu['GPU Clock'] + "', "
sql += "'" + str(gpu['Memory Clock'] + "', "
sql += "'" + str(gpu['GPU Voltage'] + "', "
sql += "'" + str(gpu['Device Hardware']) + "'"
sql += ") WHERE id='%d'", ngpu
sql += ";"
return sqlstatement
我打赌这是非常愚蠢的事情,但我无法找到它是什么。
答案 0 :(得分:4)
您在前一行缺少右括号:
sql += "'" + str(gpu['Memory Clock'] + "', "
# ----^ but not here ^
多行中缺少str()
函数的右括号。
你真的不应该使用字符串插值来构建SQL查询;您将使用SQL 参数。这是如何工作的取决于您的数据库适配器。
例如,在sqite3
中,您使用?
作为占位符; MySQLdb使用%s
代替。一个sqlite的例子是:
sql = """\
UPDATE pythondb SET (
minerid, temp, load, hashrate, accepted, rejected,
coreclock, memclock, power, hwerror)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
WHERE id=?"
"""
cursor.execute(sql, (
gpu['Temperature'], gpu['GPU Activity'], gpu['MHS av'] * 1000,
gpu['Accepted'], gpu['Rejected'], gpu['GPU Clock'], gpu['Memory Clock'],
gpu['GPU Voltage'], gpu['Device Hardware'])
)
即使您不能使用SQL参数,您也应该了解Python String Formatting;你可以拥有:
sql = """\
UPDATE pythondb SET (
minerid, temp, load, hashrate, accepted, rejected,
coreclock, memclock, power, hwerror)
VALUES (
'{0[Temperature]}', '{0[GPU Activity]}',
'{1}', '{0[Accepted]}', '{0[Rejected]}', '{0[GPU Clock]}',
'{0[Memory Clock]}', '{0[GPU Voltage]}', '{0[Device Hardware]}')
WHERE id='{2}';
""".format(gpu, gpu['MHS av'] * 1000, ngpu)
除了将SQL值插入到这样的SQL语句中仍然是一个非常糟糕的想法。