多个占位符SQLite Python无法正常工作

时间:2016-05-16 20:44:05

标签: python sqlite

我正在尝试从Track TABLE更新TrackId的UnitPrice。 UnitPrice和TrackId由用户输入给出参数。我目前收到的参数数量有误:

    Traceback (most recent call last):
    File "HW4.py", line 48, in <module>
    conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?", (n_price,t_id))
    sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

这是我的代码:

track_id = raw_input('Enter Track ID\n')
t_id = (track_id,)
cur = conn.execute("SELECT T.UnitPrice FROM Track T WHERE T.TrackId = ?", t_id)
for row in cur:
    print "Unit Price: ", row[0]

new_price = raw_input('Enter New Price\n')
n_price = (new_price,)
conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?", n_price, t_id)
conn.commit
print "Total number of rows updated: ", conn.total_changes

cur = conn.execute("SELECT T.UnitPrice FROM Track T WHERE T.TrackId = ?", t_id)
for row in cur:
    print "Unice Price: ", row[0]

我猜这是如何将n_price和t_id放入?的语法错误?占位符。

1 个答案:

答案 0 :(得分:1)

您需要将参数作为单一可迭代传递,例如列表或元组,但是您将n_price参数包装在另一个嵌套元组中

n_price = (new_price,)  # this is a tuple
conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?",
             (n_price, t_id))  # wrapping in another tuple

所以现在你传递((new_price,), t_id),但第一个元组不是受支持的类型。

在一个元组中一起传递你的参数:

params = (new_price, t_id)
conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?", params)

或使用

conn.execute("UPDATE Track set UnitPrice = ? WHERE TrackId = ?", (new_price, t_id))