23
votes

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?

5
From when I used sqlite3 in python, I remember the query and the parameters having to be separate arguments, not a single string. Maybe try that? - Patashu

5 Answers

42
votes

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.

27
votes

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

5
votes

You have a ;, in the middle of the query string - that is an invalid syntax. Pass a dictionary as a second argument to execute if you want to use a named parameter binding.

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

Try this:

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

cursor.execute(sql, (user_name, user_email))
-3
votes
import sqlite3
def DB():    
    List = {"Name":"Omar", "Age":"33"}

    columns = ', '.join("" + str(x).replace('/', '_') + "" for x in List.keys())     
    values = ', '.join("'" + str(x).replace('/', '_') + "'" for x in List.values())

    sql_qry = "INSERT INTO %s ( %s ) values (?,?) ; ( %s )" % ('Table Name', columns, values)


    conn = sqlite3.connect("DBname.db")
    curr = conn.cursor()
#     curr.execute("""create table if not exists TestTable(
#                         Name text, 
#                         Age text
#                         )""")

#     print columns
#     print values
#     print sql



    #     sql = 'INSERT INTO yell (Name , Age) values (%s, %s)'
    curr.execute(sql_qry)    
DB()