Merge remote-tracking branch 'origin/pycurl' into planetlab-4_0-branch
[plcapi.git] / trunk / psycopg2 / examples / binary.py
1 # binary.py - working with binary data
2 #
3 # Copyright (C) 2001-2004 Federico Di Gregorio  <fog@debian.org>
4 #
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
8 # version.
9 #
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
13 # for more details.
14
15 ## put in DSN your DSN string
16
17 DSN = 'dbname=test'
18
19 ## don't modify anything below tis line (except for experimenting)
20
21 import sys
22 import psycopg2
23
24 if len(sys.argv) > 1:
25     DSN = sys.argv[1]
26
27 print "Opening connection using dns:", DSN
28 conn = psycopg2.connect(DSN)
29 print "Encoding for this connection is", conn.encoding
30
31 curs = conn.cursor()
32 try:
33     curs.execute("CREATE TABLE test_binary (id int4, name text, img bytea)")
34 except:
35     conn.rollback()
36     curs.execute("DROP TABLE test_binary")
37     curs.execute("CREATE TABLE test_binary (id int4, name text, img bytea)")
38 conn.commit()
39
40 # first we try two inserts, one with an explicit Binary call and the other
41 # using a buffer on a file object.
42
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())}
47
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)
52
53 # now we try to extract the images as simple text strings
54
55 print "Extracting the images as strings..."
56 curs.execute("SELECT * FROM test_binary")
57
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])
63     print "done"
64     print "  python type of image data is", type(row[2])
65     
66 # extract exactly the same data but using a binary cursor
67
68 print "Extracting the images using a binary cursor:"
69
70 curs.execute("""DECLARE zot CURSOR FOR
71                   SELECT img, name FROM test_binary FOR READ ONLY""")
72 curs.execute("""FETCH ALL FROM zot""")
73
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])
79     print "done"
80     print "  python type of image data is", type(row[0])
81     
82 # this rollback is requires because we can't drop a table with a binary cusor
83 # declared and still open
84 conn.rollback()
85
86 curs.execute("DROP TABLE test_binary")
87 conn.commit()
88
89 print "\nNow try to load the new images, to check it worked!"