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.

Asclepius
64.7k20 gold badges188 silver badges165 bronze badges
asked Dec 5, 2010 at 19:06
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))
answered Dec 5, 2010 at 19:11
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))

answered Oct 19, 2018 at 8:20

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

Suraj Rao
29.7k11 gold badges96 silver badges104 bronze badges
answered Aug 12, 2020 at 10:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.