sqlite3 python参数传递issu

2024-10-05 17:42:27 发布

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

我有这个代码:

conn = sqlite3.connect("testDB")
curs = conn.cursor()

curs.execute("CREATE TABLE IF NOT EXISTS testTable( col1 VARCHAR, col2 VARCHAR)")
c1 = "value1"
c2 = "value2"
curs.execute("INSERT INTO testTable VALUES (?,?)", (c1, c2))#this works fine
conn.commit()

def inDB(curs, table, col, value):
    curs.execute("SELECT * FROM ? WHERE ?=?",(table, col, value)) #problemis here
    return bool(curs.fetchone())

print inDB(curs, "testTable", "col1", c1)

它给了我一个错误:

^{pr2}$

为什么这不起作用?我该如何修复它?在


Tags: 代码executevalueconnecttablecolconnsqlite3
2条回答

我只能从文件中提取:

http://www.sqlite.org/cintro.html

3.0 Binding Parameters and Reusing Prepared Statements

In SQLite, wherever it is valid to include a string literal, one can use a parameter in one of the following forms:

http://www.sqlite.org/c3ref/bind_blob.html

In the SQL statement text input to sqlite3_prepare_v2() and its variants, literals may be replaced by a parameter that matches one of following templates:

http://www.sqlite.org/lang_insert.html

SQLite INSERT

您可能无法使用参数化的表名,因为[database-name.]table-name不是普通的文本值(这就是为什么不能编写INSERT INTO 'foo'||'bar'||12 VALUES ...之类的语句)。在

或者是完全不同的东西。:)

我不确定,但我不认为您可以在表名或列名上使用绑定变量。。。在

试试看

curs.execute("INSERT INTO ? VALUES (?,?)", (testTable, c1, c2))

我敢打赌这行不通。在这种情况下,您需要避免在表名或列名上使用?。我宁愿使用连接运算符来连接字符串,就像在Java中它是“+”。例如(Java风格):

^{pr2}$

相关问题 更多 >