警告:一次只能执行一条语句

2024-04-25 15:16:42 发布

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

我在运行此代码时遇到错误:

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)

为什么会这样


Tags: the代码nameinputdbsqlrawemail
3条回答

executescript代替execute

execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call.

https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute

虽然其他海报对语句格式的描述是正确的,但由于您试图在一个查询中执行多个语句(请注意;在您的查询中分隔语句),因此您收到了此特定错误

从Python sqlite3文档:

"execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call."

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

现在,即使使用executescript(),语句也无法正确执行,因为它的格式还有其他问题(请参阅其他发布的答案)。但是您收到的错误是由于您的多个语句造成的。我将此答案发布给其他可能在搜索该错误后在此处漫游的人

在查询字符串的中间有一个^ {CD1>},这是一个无效的语法。如果要使用命名参数绑定,请将字典作为第二个参数传递给execute

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

相关问题 更多 >