我测试了你的语句,如果你的不同变量的格式正确,可以直接连接到语句字符串中,它应该可以正常工作:
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> cu = conn.cursor()
>>> cu.execute('create table foo (uID, username, password, creator_exp, location)')
<sqlite3.Cursor object at 0x7fccc2c115e0>
>>> user_ID='a'
>>> username='b'
>>> password='c'
>>> creator_exp='d'
>>> table_name='foo'
>>> cu.execute("INSERT INTO `"+table_name+"` (uID, username, password, creator_exp, location) VALUES ('"+user_ID+"', '"+username+"', '"+password+"', '"+creator_exp+"', '0-0')")
<sqlite3.Cursor object at 0x7fccc2c115e0>
当你得到它时可能不是syntax error
这样:
>>> username="'barf"
>>> cu.execute("INSERT INTO `"+table_name+"` (uID, username, password, creator_exp, location) VALUES ('"+user_ID+"', '"+username+"', '"+password+"', '"+creator_exp+"', '0-0')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: near "barf": syntax error
因此,只需使用格式化参数即可。
>>> cu.execute("INSERT INTO `"+table_name+"` (uID, username, password, creator_exp, location) VALUES (?, ?, ?, ?, '0-0')",
(user_ID, username, password, creator_exp))
<sqlite3.Cursor object at 0x7fccc2c115e0