[英]How can I create a SQLite table using the sqlite3 Python library with parameterized placeholders?
From Python's documentation ( https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute ), I should be able to execute SQL statements using parameterized placeholders.从 Python 的文档( https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute )中,我应该能够使用参数化占位符执行 SQL 语句。 Yet, the code below doesn't work.
然而,下面的代码不起作用。
import sqlite3
conn = sqlite3.connect("temp.db")
c = conn.cursor()
c.execute("create table ? (foo text, bar text)", ("table_name",))
conn.commit()
conn.close()
I'm getting an error:我收到一个错误:
Traceback (most recent call last):
File "main.py", line 6, in <module>
c.execute("create table ? (foo text, bar text)", ("table_name",))
sqlite3.OperationalError: near "?": syntax error
But if I switch out of using parameterized placeholders, it works.但是如果我不使用参数化占位符,它就可以工作。
In a word - no.一句话——不。 You can only parameterize values, not object names (in this case, the table's name).
您只能参数化值,不能参数化对象名称(在本例中为表名称)。 If you want to do something like this, you'd have to resort to string manipulation, eg:
如果你想做这样的事情,你必须求助于字符串操作,例如:
c.execute("create table %s (foo text, bar text)" % ("table_name"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.