Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert variable into sqlite database in python?

My code seems to run fine without any errors but it just creates an empty database file with nothing in it, Cant figure out what i'm doing wrong here.

import sqlite3 as lite
import sys
con = lite.connect('test43.db')

def create_db():
    with con:
        cur = con.cursor()
        cur.execute("DROP TABLE IF EXISTS Contacts")
        cur.execute("CREATE TABLE Contacts (First Name TEXT, Last Name TEXT, Phone TEXT, Email TEXT);")
        cur.execute("INSERT INTO Contacts VALUES (?, ?, ?, ?);", (firstname, lastname, phone, email))
        cur.commit()

#Get user input
print ('Enter a new contact')
print ('')
firstname = input('Enter first name: ')
lastname = input('Enter last name: ')
phone = input('Enter phone number: ')
email = input('Enter Email address: ')

createnewdb = input('Enter 1 to create new db: ')
if createnewdb == 1:
    create_db()
else:
    sys.exit(0)
like image 1000
Skilo Skilo Avatar asked Nov 03 '13 23:11

Skilo Skilo


People also ask

How do I insert data into 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.

Can you use variables in SQLite?

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.


1 Answers

I found this example for inserting variables to be very helpful.

c.execute("SELECT * FROM {tn} WHERE {idf}={my_id}".\
        format(tn=table_name, cn=column_2, idf=id_column, my_id=some_id))

Here's the link to the tutorial. http://sebastianraschka.com/Articles/2014_sqlite_in_python_tutorial.html

like image 61
EnergyGeek Avatar answered Oct 13 '22 07:10

EnergyGeek