Python语法错误无缘无故?

2024-05-14 00:54:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到以下错误:

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

我打赌这是件很愚蠢的事,但我就是找不到它是什么。你知道吗


Tags: 代码pysqldatagpudef错误line
1条回答
网友
1楼 · 发布于 2024-05-14 00:54:38

前一行缺少右括号:

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值仍然是一个非常糟糕的主意。你知道吗

相关问题 更多 >