2013-03-20 61 views
5

执行一个语句运行此代码时,我得到的错误:sqlite3.Warning:您只能在一个时间

import sqlite3 

user_name = raw_input("Please enter the name: ") 
user_email = raw_input("Please enter the email: ") 

db = sqlite3.connect("customer") 
cursor=db.cursor() 

sql = """INSERT INTO customer 
     (name, email) VALUES (?,?);, 
     (user_name, user_email)""" 

cursor.execute(sql) 

这究竟是为什么?这是一个无效的语法 -

+0

从当我在python使用sqlite3的,记得查询并不必是单独的参数,而不是一个单一的字符串的参数。也许试试? – Patashu 2013-03-20 01:51:34

回答

3

您在查询字符串中间有一个;,。如果要使用命名参数绑定,请将字典作为第二个参数传递给execute

sql = "INSERT INTO customer (name, email) VALUES (:name, :email)" 
cursor.execute(sql, {'name':user_name, 'email':user_email}) 
+0

它的工作原理。但我不明白为什么这不起作用: 'sql =“INSERT INTO客户(名称,电子邮件)VALUES(user_name,user_email)” cursor.execute(sql)' – spamup 2013-03-20 12:40:04

+0

因为您不是插值参数查询。它应该是像'sql =“类似的东西INSERT INTO客户(姓名,电子邮件)VALUES('%s','%s')”%(user_name,user_email)' – 2013-03-20 13:28:41

0

及彼http://zetcode.com/db/sqlitepythontutorial/尝试:

import sqlite3 

user_name = raw_input("Please enter the name: ") 
user_email = raw_input("Please enter the email: ") 

db = sqlite3.connect("customer") 
with db: 
    cursor=db.cursor() 

    cursor.execute("INSERT INTO customer (name TEXT, email TEXT)") 
    cursor.execute("INSERT INTO customer VALUES ({0}, {1})" .format(user_name, user_email)) 
13

虽然其他海报是关于你的声明的格式,因为你正试图在一个查询中执行多个语句您收到此特定错误正确(注意;在分隔语句的查询中)。

从Python的sqlite3的文档:。

“的execute()将只执行一个SQL语句如果你尝试用它来执行一个以上的 声明,它会抛出一个警告,使用executescript()如果你想通过一次调用来执行多个SQL语句“ ”。

https://docs.python.org/2/library/sqlite3.html

现在,您的发言不会正确执行,即使你使用executescript(),因为它存在格式化的方式等问题(见其他答案公布)。但是,您收到的错误是因为您的多条语句。我在发布这个答案的时候可能会在搜索那个错误后在这里流浪。