Re: [pysqlite] python an sqlite objects

Gerhard Häring <[email protected]> Wed, 03 Dec 2008 22:21:54 +0100
Newsgroups gmane.comp.python.db.pysqlite.user
Message-ID <[email protected]>
azrael wrote:
> It logical that it would be more efficient and logical to use a object
> oriented database, but in this case I ask because of the portable
> nature of sqlite.
> 
> so, if I get it right, this should be possible [...]

Did you try it? Did it work? If so,it was pure luck. Attached is a 
script that shows how to do it right.

-- Gerhard

_______________________________________________
list-pysqlite mailing list
list-pysqlite-FR6EJeJVuqdwc357pe9rcyQmJico6nz3epZhswDD4dQ@public.gmane.org
http://itsystementwicklung.de/cgi-bin/mailman/listinfo/list-pysqlite
sqlite_serialize.py (text/x-python, 1.6 KB)
# This is an example for storing pickleable Python objects in a SQLite
# database

import cPickle as pickle

try:
    from pysqlite2 import dbapi2 as sqlite3
except ImportError:
    import sqlite3

class Point(object):
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "<Point(%s, %s)>" % (self.x, self.y)

def test():
    con = sqlite3.connect(":memory:")
    cur = con.cursor()

    # Make sure you store your pickled 
    # cur.execute("create table pickled(id integer primary key, data blob)")
    cur.execute("create table pickled(id integer primary key, data blob)")

    # Here we force pickle to use the efficient binary protocol
    # (protocol=2). This means you absolutely must use an SQLite BLOB field
    # and make sure you use sqlite3.Binary() to bind a BLOB parameter.
    p1 = Point(3, 4)
    cur.execute("insert into pickled(data) values (?)", (sqlite3.Binary(pickle.dumps(p1, protocol=2)),))

    # If we use old pickle protocol (protocol=0, which is also the default),
    # we get away with sending ASCII bytestrings to SQLite.
    p2 = Point(-5, 3.12)
    cur.execute("insert into pickled(data) values (?)", (pickle.dumps(p2, protocol=0),))

    # Fetch the BLOBs back from SQLite
    cur.execute("select data from pickled")
    for row in cur:
        serialized_point = row[0]

        # Deserialize the BLOB to a Python object - # pickle.loads() needs a
        # bytestring.
        point = pickle.loads(str(serialized_point))
        print "got point back from database", point

if __name__ == "__main__":
    test()