By Nikolai Shokhirev http://www.numericalexpert.com./
SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If you want to use other types you must add support for them yourself.
This includes the following steps:
SQLite3 comes with support of DATE and TIMESTAMP (datetime) types (see dbapi2.py). The DATE field accepts a sring in ISO 8601 format 'YYYY-MM-DD' or datetime.date object:
import sqlite3
from datetime import datetime, date
conn = sqlite3.connect("person_db.sqlite",detect_types=sqlite3.PARSE_DECLTYPES)
conn.execute("CREATE TABLE person (id integer primary key, firstname text, lastname text, dob date)")
he TIMESTAMP field accepts a sring in ISO 8601 format 'YYYY-MM-DD HH:MM:SS.mmmmmm' or datetime.datetime object:
conn.execute("INSERT INTO person(firstname, lastname, dob) values (?, ?, ?)", ("Joe","Doe","2003-06-25"))
d = date(1723,06,05)
conn.execute("INSERT INTO person(firstname, lastname, dob) values (?, ?, ?)", ("Adam","Smith", d))
conn.commit()
cur = conn.cursor()
cur.execute("SELECT * FROM person")
print cur.fetchone()
print cur.fetchone()
conn.close()
conn = sqlite3.connect("log_db.sqlite",detect_types=sqlite3.PARSE_DECLTYPES)
conn.execute("CREATE TABLE logs (id integer primary key, message text, [timestamp] timestamp)")
The TIMESTAMP field accepts a sring in ISO 8601 format 'YYYY-MM-DD HH:MM:SS.mmmmmm' or datetime.datetime object:
conn.execute("INSERT INTO logs(message, timestamp) values (?, ?)", ("message: error",'2012-12-25 23:59:59'))
conn.execute("INSERT INTO logs(message, timestamp) values (?, ?)", ("message: ok", datetime.now()))
conn.commit()
cur = conn.cursor()
cur.execute("SELECT * FROM logs")
print cur.fetchone()
print cur.fetchone()
conn.close()
from decimal import Decimal
The adapter accepts as single parameter the Python value, and must return a value of the following types: int, long, float, str or buffer.
def decimal2float(val):
return float(str(val))
sqlite3.register_adapter(Decimal, decimal2float)
conn = sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_DECLTYPES)
conn.execute("CREATE TABLE numbers (number decimal)")
conn.execute("INSERT INTO numbers(number) values (?)", (Decimal('123.456789'),))
conn.commit()
cur = conn.cursor()
cur.execute("SELECT * FROM numbers")
print cur.fetchone()
conn.close()
To retrieve numbers as a Decimal, we have to implement and register a converter.
def float2decimal(val):
return Decimal(str(val))
sqlite3.register_converter("decimal", float2decimal)
conn = sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_DECLTYPES)
conn.execute("CREATE TABLE numbers (number decimal)")
conn.execute("INSERT INTO numbers(number) values (?)", (Decimal('123.456789'),))
conn.commit()
cur = conn.cursor()
cur.execute("SELECT * FROM numbers")
print cur.fetchone()
conn.close()
conn = sqlite3.connect("person_db.sqlite",detect_types=sqlite3.PARSE_DECLTYPES)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM person where id=6")
for row in cur:
print row['firstname']
print 'DoB:', row['dob']
conn.close()
# example from http://docs.python.org/2.7/library/sqlite3.html
con = sqlite3.connect(":memory:")
con.execute("create table person (id integer primary key, firstname varchar unique)")
# Successful, con.commit() is called automatically afterwards
with con:
con.execute("insert into person(firstname) values (?)", ("Joe",))
# con.rollback() is called after the with block finishes with an exception, the
# exception is still raised and must be caught
try:
with con:
con.execute("insert into person(firstname) values (?)", ("Joe",))
except sqlite3.IntegrityError:
print "couldn't add Joe twice"