python / SQL语法问题

时间:2012-05-06 09:38:48

标签: python sql database sqlite

我在调用此SQL命令时遇到问题,我得到:'OperationalError:near“'0-0'”:语法错误'

我的电话如下:

users_db_curs.execute("INSERT INTO `"+table_name+"` (uID, username, password, creator_exp, location) 
VALUES ('"+user_ID+"', '"+username+"', '"+password+"', '"+creator_exp+"', '0-0')")

2 个答案:

答案 0 :(得分:1)

我测试了你的语句,它应该可以正常工作如果你的不同变量被正确格式化为直接连接在语句字符串litteral中:

>>> 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

It's probably not the case

>>> 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

所以请改用formatted parameters

>>> 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

答案 1 :(得分:0)

con = sqlite.connect(db_name)
cur = con.cursor()

with con:
   cur.execute("INSERT INTO ? VALUES(?, ?, ?, ?, ?)",
       (table_name, user_ID, username, password, creator_exp))

应该工作了 您应该阅读Zetcode's tutorial