Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python + sqlite, insert data from variables into table

Tags:

python

sql

sqlite

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.

like image 266
steini Avatar asked Dec 05 '10 19:12

steini


People also ask

How do I add data to a SQLite database in Python?

First, connect to the SQLite database by creating a Connection object. Second, create a Cursor object by calling the cursor method of the Connection object. Third, execute an INSERT statement. If you want to pass arguments to the INSERT statement, you use the question mark (?) as the placeholder for each argument.

How do you write a dynamic INSERT query in Python?

def populate_table(table_name, data): #Grab first tuple and find out how many columns are expected to be edited num_columns = len(data[0]) try: cursor. executemany("INSERT INTO {} VALUES({})". format(table_name, ','.


2 Answers

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

cur.execute("insert into contacts (name, phone, email) values (?, ?, ?)",
            (name, phone, email))
like image 110
Mark Byers Avatar answered Oct 04 '22 03:10

Mark Byers


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

like image 23
pro1991 Avatar answered Oct 04 '22 03:10

pro1991