1 # binary.py - working with binary data
3 # Copyright (C) 2001-2004 Federico Di Gregorio <fog@debian.org>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2, or (at your option) any later
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 ## put in DSN your DSN string
19 ## don't modify anything below tis line (except for experimenting)
27 print "Opening connection using dns:", DSN
28 conn = psycopg2.connect(DSN)
29 print "Encoding for this connection is", conn.encoding
33 curs.execute("CREATE TABLE test_binary (id int4, name text, img bytea)")
36 curs.execute("DROP TABLE test_binary")
37 curs.execute("CREATE TABLE test_binary (id int4, name text, img bytea)")
40 # first we try two inserts, one with an explicit Binary call and the other
41 # using a buffer on a file object.
43 data1 = {'id':1, 'name':'somehackers.jpg',
44 'img':psycopg2.Binary(open('somehackers.jpg').read())}
45 data2 = {'id':2, 'name':'whereareyou.jpg',
46 'img':buffer(open('whereareyou.jpg').read())}
48 curs.execute("""INSERT INTO test_binary
49 VALUES (%(id)s, %(name)s, %(img)s)""", data1)
50 curs.execute("""INSERT INTO test_binary
51 VALUES (%(id)s, %(name)s, %(img)s)""", data2)
53 # now we try to extract the images as simple text strings
55 print "Extracting the images as strings..."
56 curs.execute("SELECT * FROM test_binary")
58 for row in curs.fetchall():
59 name, ext = row[1].split('.')
60 new_name = name + '_S.' + ext
61 print " writing %s to %s ..." % (name+'.'+ext, new_name),
62 open(new_name, 'wb').write(row[2])
64 print " python type of image data is", type(row[2])
66 # extract exactly the same data but using a binary cursor
68 print "Extracting the images using a binary cursor:"
70 curs.execute("""DECLARE zot CURSOR FOR
71 SELECT img, name FROM test_binary FOR READ ONLY""")
72 curs.execute("""FETCH ALL FROM zot""")
74 for row in curs.fetchall():
75 name, ext = row[1].split('.')
76 new_name = name + '_B.' + ext
77 print " writing %s to %s ..." % (name+'.'+ext, new_name),
78 open(new_name, 'wb').write(row[0])
80 print " python type of image data is", type(row[0])
82 # this rollback is requires because we can't drop a table with a binary cusor
83 # declared and still open
86 curs.execute("DROP TABLE test_binary")
89 print "\nNow try to load the new images, to check it worked!"