18

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
  • 1
    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? Commented Dec 5, 2010 at 19:12
  • 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 Commented Dec 5, 2010 at 19:25
  • 6
    Please accept Mark's answer, or post another solution yourself and accept that. Using [solved] in the title is not usual here. Thanks! Commented Dec 5, 2010 at 19:35

3 Answers 3

64

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

cur.execute("insert into contacts (name, phone, email) values (?, ?, ?)",
            (name, phone, email))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you sir,I had been trying some variations of that but this works :D
can i use a list [name, phone, email] instead of a set (name, phone, email) ?
@AmeyPNaik I think it needs a tuple
1

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

1 Comment

Usually it's better to explain a solution instead of just posting some rows of anonymous code. You can read How do I write a good answer, and also Explaining entirely code-based answers
1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.