15 little snippets here found on the web ... edited some and updated to now run in Python 3.3.2 ...
# PythonSqlite3.py # # this version 2013-07-15 #
'''
15 little demo's here ...
found at:
http://zetcode.com/db/sqlitepythontutorial/
fixed/edited to run on Python 3.3 by dwz on 2013-07-15
'''
import sqlite3 as lite
import sys
con = None
try:
con = lite.connect( 'test.db' )
cur = con.cursor()
cur.execute( 'SELECT SQLITE_VERSION()' )
data = cur.fetchone()
print( "SQLite version: %s" % data )
except(lite.Error, e):
print( "Error %s:" % e.args[0] )
sys.exit(1)
finally:
if con:
con.close()
input( "1. Press 'Enter' to continue ... " )
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute( 'SELECT SQLITE_VERSION()' )
data = cur.fetchone()
print( "SQLite version: %s" % data )
'''
input( "2. Press 'Enter' to continue ... " )
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)")
cur.execute("INSERT INTO Cars VALUES(2,'Mercedes',57127)")
cur.execute("INSERT INTO Cars VALUES(3,'Skoda',9000)")
cur.execute("INSERT INTO Cars VALUES(4,'Volvo',29000)")
cur.execute("INSERT INTO Cars VALUES(5,'Bentley',350000)")
cur.execute("INSERT INTO Cars VALUES(6,'Citroen',21000)")
cur.execute("INSERT INTO Cars VALUES(7,'Hummer',41400)")
cur.execute("INSERT INTO Cars VALUES(8,'Volkswagen',21600)")
'''
'''
These two lines insert two cars into the table.
Using the with keyword, the changes are automatically committed.
Otherwise, we would have to commit them manually.
'''
input( "3. Press 'Enter' to continue ... " )
#import sqlite3 as lite
#import sys
cars = (
(1, 'Audi', 52642),
(2, 'Mercedes', 57127),
(3, 'Skoda', 9000),
(4, 'Volvo', 29000),
(5, 'Bentley', 350000),
(6, 'Hummer', 41400),
(7, 'Volkswagen', 21600)
)
#print cars
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Cars")
cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
cur.executemany("INSERT INTO Cars VALUES(?, ?, ?)", cars)
input( "4. Press 'Enter' to continue ... " )
#import sqlite3 as lite
#import sys
try:
con = lite.connect('test.db')
cur = con.cursor()
cur.executescript("""
DROP TABLE IF EXISTS Cars;
CREATE TABLE Cars(Id INT, Name TEXT, Price INT);
INSERT INTO Cars VALUES(1,'Audi',52642);
INSERT INTO Cars VALUES(2,'Mercedes',57127);
INSERT INTO Cars VALUES(3,'Skoda',9000);
INSERT INTO Cars VALUES(4,'Volvo',29000);
INSERT INTO Cars VALUES(5,'Bentley',350000);
INSERT INTO Cars VALUES(6,'Citroen',21000);
INSERT INTO Cars VALUES(7,'Hummer',41400);
INSERT INTO Cars VALUES(8,'Volkswagen',21600);
""")
con.commit()
except( lite.Error, e ):
if con:
con.rollback()
print( "Error %s:" % e.args[0] )
sys.exit(1)
finally:
if con:
con.close()
input( "5. Press 'Enter' to continue ... " )
#import sqlite3 as lite
#import sys
con = lite.connect(':memory:')
with con:
cur = con.cursor()
cur.execute("CREATE TABLE Friends(Id INTEGER PRIMARY KEY, Name TEXT);")
cur.execute("INSERT INTO Friends(Name) VALUES ('Tom');")
cur.execute("INSERT INTO Friends(Name) VALUES ('Rebecca');")
cur.execute("INSERT INTO Friends(Name) VALUES ('Jim');")
cur.execute("INSERT INTO Friends(Name) VALUES ('Robert');")
lid = cur.lastrowid
print( "The last Id of the inserted row is %d" % lid )
input( "6. Press 'Enter' to continue ... " )
#import sqlite3 as lite
#import sys
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM Cars")
rows = cur.fetchall()
for row in rows:
print( row )
input( "7. Press 'Enter' to continue ... " )
#import sqlite3 as lite
#import sys
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM Cars")
print( "%s %20s %6s" % ("ID", "NAME", "PRICE" ) )
while True:
row = cur.fetchone()
if row == None:
break
print( "%2i %20s %6i" % (row[0], row[1], row[2]) )
input( "8. Press 'Enter' to continue ... " )
#import sqlite3 as lite
con = lite.connect('test.db')
with con:
# We select a dictionary cursor.
con.row_factory = lite.Row
cur = con.cursor()
cur.execute("SELECT * FROM Cars order by -Price") #descending order
rows = cur.fetchall()
print( "%s %20s %6s" % ("ID", "NAME", "PRICE" ) )
for row in rows:
# Now we can access records by the names of columns.
print( "%2s %20s %6s" % (row["Id"], row["Name"], row["Price"]) )
input( "9. Press 'Enter' to continue ... " )
'''
Parameterized queries ...
Now we will concern ourselves with parameterized queries.
When we use parameterized queries, we use placeholders
instead of directly writing the values into the statements.
Parameterized queries increase security and performance.
The Python sqlite3 module supports two types of placeholders.
Question marks and named placeholders.
'''
#import sqlite3 as lite
#import sys
con = lite.connect('test.db')
uId = 1
uPrice = 62300
with con:
cur = con.cursor()
# We update a price of one car.
# In this code example, we use the question mark placeholders.
cur.execute("UPDATE Cars SET Price=? WHERE Id=?", (uPrice, uId))
con.commit()
print( "Number of rows updated: %d" % cur.rowcount )
cur.execute("SELECT * FROM Cars order by -Price")
print( "%s %20s %6s" % ("ID", "NAME", "PRICE" ) )
while True:
row = cur.fetchone()
if row == None:
break
print( "%2i %20s %6i" % (row[0], row[1], row[2]) )
input( "10. Press 'Enter' to continue ... " )
#import sqlite3 as lite
#import sys
uId = 4
con = lite.connect('test.db')
with con:
cur = con.cursor()
# The second example uses parameterized statements
# with named placeholders.
# We select a name and a price of a car using named placeholders
cur.execute("SELECT Name, Price FROM Cars WHERE Id=:Id", {"Id": uId})
con.commit()
row = cur.fetchone()
print( row[0], row[1] )
input( "11. Press 'Enter' to continue ... " )
'''
import sqlite3 as lite
import sys
In this script, we read an image from the current
working directory and write it into the Images table
of the SQLite test.db database.
'''
def readImage():
try:
fin = open("woman.jpeg", "rb")
img = fin.read()
print( "\nimg read ok ..." )
return img
except( IOError, e ):
print( "Error %d: %s" % (e.args[0], e.args[1]) )
sys.exit(1)
finally:
if fin:
fin.close()
try:
con = lite.connect('test.db')
cur = con.cursor()
data = readImage()
binary = lite.Binary(data)
cur.execute("DROP TABLE IF EXISTS Images")
cur.execute("CREATE TABLE Images(Data BINARY)")
#cur.execute("INSERT INTO Cars VALUES(8,'Volkswagen',21600)")
cur.execute("INSERT INTO Images(Data) VALUES (?)", (binary,) )
con.commit()
except( lite.Error, e ):
if con:
con.rollback()
print( "Error %s:" % e.args[0] )
sys.exit(1)
finally:
if con:
con.close()
input( "12. Press 'Enter' to continue ... " )
'''
In this section, we are going to perform the reverse operation.
We will read an image from the database table.
import sqlite3 as lite
import sys
'''
def writeImage(data):
try:
fout = open('woman2.jpg','wb')
fout.write(data)
except( IOError, e ):
print( "Error %d: %s" % (e.args[0], e.args[1]) )
sys.exit(1)
finally:
if fout:
fout.close()
try:
con = lite.connect('test.db')
cur = con.cursor()
cur.execute("SELECT Data FROM Images LIMIT 1")
data = cur.fetchone()[0]
# We read image data from the Images table
# and write it to another file, which we call woman2.jpg.
writeImage(data)
except( lite.Error, e ):
print( "Error %s:" % e.args[0] )
sys.exit(1)
finally:
if con:
con.close()
input( "13. Press 'Enter' to continue ... " )
'''
import sqlite3 as lite
import sys
'''
con = lite.connect('test.db')
with con:
cur = con.cursor()
# In this example, we issue the PRAGMA table_info(tableName) command,
# to get some metadata info about our Cars table.
cur.execute('PRAGMA table_info(Cars)')
data = cur.fetchall()
for d in data:
print( d[0], d[1], d[2] )
input( "14. Press 'Enter' to continue ... " )
'''
import sqlite3 as lite
import sys
Next we will print all rows from the Cars table with their column names.
'''
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute('SELECT * FROM Cars order by -Price') # ordered in descending order #
col_names = [cn[0] for cn in cur.description] # make a Python list of col names #
rows = cur.fetchall()
# Now, we include the names of the columns too.
print( "%s %-10s %8s" % (col_names[0], col_names[1], col_names[2]) )
for row in rows:
# We print the contents of the Cars table to the console.
# The records are aligned with the column names.
print( "%2s %-10s %8s" % row )
input( "15. Press 'Enter' to continue ... " )
'''
In our last example related to the metadata,
we will list all tables in the test.db database.
import sqlite3 as lite
import sys
'''
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute( "SELECT name FROM sqlite_master WHERE type = 'table'" )
tables = cur.fetchall()
# The code example prints all available tables in the current database to the console.
for table in tables:
print( table[0] )
input( "\nPress 'Enter' to continue / EXIT --- > )