steini
steini

Reputation: 181

python + sqlite, insert data from variables into table

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.

Upvotes: 18

Views: 91009

Answers (3)

Sameer Ranjan Sahoo
Sameer Ranjan Sahoo

Reputation: 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

Upvotes: 0

pro1991
pro1991

Reputation: 43

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

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839114

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

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

Upvotes: 64

Related Questions