Storing objects in relational database
Jerry Hill
malaclypse2 at gmail.com
Fri May 23 22:45:11 EDT 2008
On Fri, May 23, 2008 at 5:07 PM, nayden <nayden at gmail.com> wrote:
> The reason I am writing here is that I can't seem to figure out how to
> save/restore python objects into a relational database.
Here's a basic version using the sqlite bindings included with Python 2.5:
import sqlite3, pickle
thing = {'date': '2008-05-21',
'event': 'Something happened this day'}
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('''create table stuff (idx integer, data text)''')
c.execute('''insert into stuff values (?,?)''', (1, pickle.dumps(thing)))
c.execute('''select data from stuff where idx=1''')
row = c.fetchone()
# sqlite3 stores text fields as unicode, so we need to encode to ascii
# before we unpickle
pickle_str = row[0].encode('ascii')
thing2 = pickle.loads(pickle_str)
print thing
print thing2
Maybe that will set you on the right track.
--
Jerry
More information about the Python-list
mailing list