Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3.Warning: You can only execute one statement at a time

Tags:

python

sqlite

I get the error when running this code:

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) 

Why is this happening?

like image 716
spamup Avatar asked Mar 20 '13 01:03

spamup


People also ask

How to execute multiple queries in sqlite3?

In SQLite using the executescript() method, we can execute multiple SQL statements/queries at once. The basic execute() method allows us to only accept one query at a time, so when you need to execute several queries we need to arrange them like a script and pass that script to the executescript() method.

What is cursor in sqlite3?

The sqlite3. Cursor class is an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries. You can create Cursor object using the cursor() method of the Connection object/class.


2 Answers

While the other posters are correct about your statement formatting you are receiving this particular error because you are attempting to perform multiple statements in one query (notice the ; in your query which separates statements).

From Python sqlite3 docs:

"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

Now your statement will not execute properly even if you use executescript() because there are other issues with the way it is formatted (see other posted answers). But the error you are receiving is specifically because of your multiple statements. I am posting this answer for others that may have wandered here after searching for that error.

like image 181
rev Avatar answered Sep 18 '22 20:09

rev


Use executescript instead of 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

like image 30
Anupam Srivastava Avatar answered Sep 21 '22 20:09

Anupam Srivastava