Python sqlite3 package
Python has a built-in package called sqlite3 that implements SQLite.
Basic Workflow
Connect to a database: A
Connectionobject represents the database.import sqlite3 conn = sqlite3.connect('example.db')Create a cursor: A
Cursorobject is used to interact with the database.c = conn.cursor()Execute SQL commands:
c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')Insert data:
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")To insert many records, use
executemany:purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)Using
?as a placeholder is important to prevent SQL injection attacks.Commit the changes:
conn.commit()Query the database:
for row in c.execute('SELECT * FROM stocks ORDER BY price'): print(row)Close the connection:
conn.close()
Important point: Unlike many other RDBMSs, SQLite does not allow multiple connections to the same database at the same time.