17
votes

I can insert hardcoded values into an SQLite table with no problem, but I'm trying to do something like this:

name = input("Name: ")
phone = input("Phone number: ")
email = input("Email: ")

cur.execute("create table contacts (name, phone, email)")
cur.execute("insert into contacts (name, phone, email) values"), (name, phone, email)

I know this is wrong, and I can't find how to make it work. Maybe someone could point me in the right direction.

3
There are tons of obvious syntax errors in your code (you can even see it from the incorrect syntax highlighting). What error do you get? Is this the actual code you are running? If not, can you please post the actual code you tried? - Mark Byers
this is not what I'm running, I just quickly typed it up for this post, just so people would get an idea what I'm trying to accomplish - steini
Please accept Mark's answer, or post another solution yourself and accept that. Using [solved] in the title is not usual here. Thanks! - Arjan

3 Answers

60
votes

You can use ? to represent a parameter in an SQL query:

cur.execute("insert into contacts (name, phone, email) values (?, ?, ?)",
            (name, phone, email))
0
votes

cur.executemany("insert into contacts (name, phone, email) values (?, ?, ?)", (name, phone, email))

0
votes
cur.execute("create table contacts (name, phone, email)")

cur.execute("insert into contacts (name, phone, email) values(?,?,?)",(name, phone, email)) 

OR

cur.execute("insert into contacts values(?,?,?)",(name, phone, email))

As you are inserting values to all available fields, its okay not to mention columns name in insert query