summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/binary.py23
-rw-r--r--examples/copy_to.py33
-rw-r--r--examples/dialtone.py12
-rw-r--r--examples/dict.py40
-rw-r--r--examples/dt.py20
-rw-r--r--examples/encoding.py52
-rw-r--r--examples/fetch.py14
-rw-r--r--examples/lastrowid.py10
-rw-r--r--examples/lobject.py38
-rw-r--r--examples/mogrify.py16
-rw-r--r--examples/myfirstrecipe.py4
-rw-r--r--examples/notify.py10
-rw-r--r--examples/simple.py10
-rw-r--r--examples/threads.py8
-rw-r--r--examples/typecast.py14
-rw-r--r--examples/tz.py20
-rw-r--r--examples/usercast.py12
17 files changed, 169 insertions, 167 deletions
diff --git a/examples/binary.py b/examples/binary.py
index 665d962..df5d1ea 100644
--- a/examples/binary.py
+++ b/examples/binary.py
@@ -17,6 +17,7 @@
DSN = 'dbname=test'
## don't modify anything below this line (except for experimenting)
+from __future__ import print_function
import sys
import psycopg2
@@ -24,9 +25,9 @@ import psycopg2
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
curs = conn.cursor()
try:
@@ -52,20 +53,20 @@ curs.execute("""INSERT INTO test_binary
# now we try to extract the images as simple text strings
-print "Extracting the images as strings..."
+print("Extracting the images as strings...")
curs.execute("SELECT * FROM test_binary")
for row in curs.fetchall():
name, ext = row[1].split('.')
new_name = name + '_S.' + ext
- print " writing %s to %s ..." % (name+'.'+ext, new_name),
+ print(" writing %s to %s ..." % (name+'.'+ext, new_name), end=' ')
open(new_name, 'wb').write(row[2])
- print "done"
- print " python type of image data is", type(row[2])
+ print("done")
+ print(" python type of image data is", type(row[2]))
# extract exactly the same data but using a binary cursor
-print "Extracting the images using a binary cursor:"
+print("Extracting the images using a binary cursor:")
curs.execute("""DECLARE zot CURSOR FOR
SELECT img, name FROM test_binary FOR READ ONLY""")
@@ -74,10 +75,10 @@ curs.execute("""FETCH ALL FROM zot""")
for row in curs.fetchall():
name, ext = row[1].split('.')
new_name = name + '_B.' + ext
- print " writing %s to %s ..." % (name+'.'+ext, new_name),
+ print(" writing %s to %s ..." % (name+'.'+ext, new_name), end=' ')
open(new_name, 'wb').write(row[0])
- print "done"
- print " python type of image data is", type(row[0])
+ print("done")
+ print(" python type of image data is", type(row[0]))
# this rollback is required because we can't drop a table with a binary cursor
# declared and still open
@@ -86,4 +87,4 @@ conn.rollback()
curs.execute("DROP TABLE test_binary")
conn.commit()
-print "\nNow try to load the new images, to check it worked!"
+print("\nNow try to load the new images, to check it worked!")
diff --git a/examples/copy_to.py b/examples/copy_to.py
index 34c9071..d5cd0ff 100644
--- a/examples/copy_to.py
+++ b/examples/copy_to.py
@@ -18,6 +18,7 @@
DSN = 'dbname=test'
## don't modify anything below this line (except for experimenting)
+from __future__ import print_function
import sys
import os
@@ -27,9 +28,9 @@ import psycopg2
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
curs = conn.cursor()
try:
@@ -51,52 +52,52 @@ conn.commit()
# copy_to using defaults
io = open('copy_to.txt', 'w')
curs.copy_to(io, 'test_copy')
-print "1) Copy %d records into file object using defaults: " % len (data) + \
- "sep = \\t and null = \\N"
+print("1) Copy %d records into file object using defaults: " % len (data) + \
+ "sep = \\t and null = \\N")
io.close()
rows = open('copy_to.txt', 'r').readlines()
-print " File has %d rows:" % len(rows)
+print(" File has %d rows:" % len(rows))
for r in rows:
- print " ", r,
+ print(" ", r, end=' ')
# copy_to using custom separator
io = open('copy_to.txt', 'w')
curs.copy_to(io, 'test_copy', ':')
-print "2) Copy %d records into file object using sep = :" % len(data)
+print("2) Copy %d records into file object using sep = :" % len(data))
io.close()
rows = open('copy_to.txt', 'r').readlines()
-print " File has %d rows:" % len(rows)
+print(" File has %d rows:" % len(rows))
for r in rows:
- print " ", r,
+ print(" ", r, end=' ')
# copy_to using custom null identifier
io = open('copy_to.txt', 'w')
curs.copy_to(io, 'test_copy', null='NULL')
-print "3) Copy %d records into file object using null = NULL" % len(data)
+print("3) Copy %d records into file object using null = NULL" % len(data))
io.close()
rows = open('copy_to.txt', 'r').readlines()
-print " File has %d rows:" % len(rows)
+print(" File has %d rows:" % len(rows))
for r in rows:
- print " ", r,
+ print(" ", r, end=' ')
# copy_to using custom separator and null identifier
io = open('copy_to.txt', 'w')
curs.copy_to(io, 'test_copy', ':', 'NULL')
-print "4) Copy %d records into file object using sep = : and null ) NULL" % \
- len(data)
+print("4) Copy %d records into file object using sep = : and null ) NULL" % \
+ len(data))
io.close()
rows = open('copy_to.txt', 'r').readlines()
-print " File has %d rows:" % len(rows)
+print(" File has %d rows:" % len(rows))
for r in rows:
- print " ", r,
+ print(" ", r, end=' ')
curs.execute("DROP TABLE test_copy")
os.unlink('copy_to.txt')
diff --git a/examples/dialtone.py b/examples/dialtone.py
index f20d6fe..f588eff 100644
--- a/examples/dialtone.py
+++ b/examples/dialtone.py
@@ -86,12 +86,12 @@ persistent_fields = {'Album': ['album_id', 'creation_time', 'binary_data'],
'Order': ['order_id', 'items', 'price']
}
-print adapt(Album()).generateInsert()
-print adapt(Album()).generateInsert()
-print adapt(Album()).generateInsert()
-print adapt(Order()).generateInsert()
-print adapt(Order()).generateInsert()
-print adapt(Order()).generateInsert()
+print(adapt(Album()).generateInsert())
+print(adapt(Album()).generateInsert())
+print(adapt(Album()).generateInsert())
+print(adapt(Order()).generateInsert())
+print(adapt(Order()).generateInsert())
+print(adapt(Order()).generateInsert())
"""
- Discussion
diff --git a/examples/dict.py b/examples/dict.py
index 1503722..b5d0b3a 100644
--- a/examples/dict.py
+++ b/examples/dict.py
@@ -25,41 +25,41 @@ import psycopg2.extras
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
curs = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
curs.execute("SELECT 1 AS foo, 'cip' AS bar, date(now()) as zot")
-print "Cursor's row factory is", curs.row_factory
+print("Cursor's row factory is", curs.row_factory)
data = curs.fetchone()
-print "The type of the data row is", type(data)
-print "Some data accessed both as tuple and dict:"
-print " ", data['foo'], data['bar'], data['zot']
-print " ", data[0], data[1], data[2]
+print("The type of the data row is", type(data))
+print("Some data accessed both as tuple and dict:")
+print(" ", data['foo'], data['bar'], data['zot'])
+print(" ", data[0], data[1], data[2])
# execute another query and demostrate we can still access the row
curs.execute("SELECT 2 AS foo")
-print "The type of the data row is", type(data)
-print "Some more data accessed both as tuple and dict:"
-print " ", data['foo'], data['bar'], data['zot']
-print " ", data[0], data[1], data[2]
+print("The type of the data row is", type(data))
+print("Some more data accessed both as tuple and dict:")
+print(" ", data['foo'], data['bar'], data['zot'])
+print(" ", data[0], data[1], data[2])
curs = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
curs.execute("SELECT 1 AS foo, 'cip' AS bar, date(now()) as zot")
-print "Cursor's row factory is", curs.row_factory
+print("Cursor's row factory is", curs.row_factory)
data = curs.fetchone()
-print "The type of the data row is", type(data)
-print "Some data accessed both as tuple and dict:"
-print " ", data['foo'], data['bar'], data['zot']
-print " ", "No access using indices: this is a specialized cursor."
+print("The type of the data row is", type(data))
+print("Some data accessed both as tuple and dict:")
+print(" ", data['foo'], data['bar'], data['zot'])
+print(" ", "No access using indices: this is a specialized cursor.")
# execute another query and demostrate we can still access the row
curs.execute("SELECT 2 AS foo")
-print "The type of the data row is", type(data)
-print "Some more data accessed both as tuple and dict:"
-print " ", data['foo'], data['bar'], data['zot']
-print " ", "No access using indices: this is a specialized cursor."
+print("The type of the data row is", type(data))
+print("Some more data accessed both as tuple and dict:")
+print(" ", data['foo'], data['bar'], data['zot'])
+print(" ", "No access using indices: this is a specialized cursor.")
diff --git a/examples/dt.py b/examples/dt.py
index 4c2a9a0..34b25b3 100644
--- a/examples/dt.py
+++ b/examples/dt.py
@@ -28,7 +28,7 @@ from psycopg2.extensions import adapt
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
curs = conn.cursor()
@@ -52,9 +52,9 @@ mx1 = (
from psycopg2.extensions import adapt
import psycopg2.extras
-print adapt(mx1)
+print(adapt(mx1))
-print "Inserting mx.DateTime values..."
+print("Inserting mx.DateTime values...")
curs.execute("INSERT INTO test_dt VALUES (%s, %s, %s, %s, %s)", mx1)
# build and insert some values using the datetime adapters
@@ -65,11 +65,11 @@ dt1 = (
datetime.datetime(2004, 10, 19, 0, 11, 17, 500000),
datetime.timedelta(13, 15*3600+17*60+59, 900000))
-print "Inserting Python datetime values..."
+print("Inserting Python datetime values...")
curs.execute("INSERT INTO test_dt VALUES (%s, %s, %s, %s, %s)", dt1)
# now extract the row from database and print them
-print "Extracting values inserted with mx.DateTime wrappers:"
+print("Extracting values inserted with mx.DateTime wrappers:")
curs.execute("SELECT d, t, dt, z FROM test_dt WHERE k = 1")
for n, x in zip(mx1[1:], curs.fetchone()):
try:
@@ -80,10 +80,10 @@ for n, x in zip(mx1[1:], curs.fetchone()):
except:
s = repr(n) + "\n -> " + str(adapt(n)) + \
"\n -> " + repr(x) + "\n -> " + str(x)
- print s
-print
+ print(s)
+print()
-print "Extracting values inserted with Python datetime wrappers:"
+print("Extracting values inserted with Python datetime wrappers:")
curs.execute("SELECT d, t, dt, z FROM test_dt WHERE k = 2")
for n, x in zip(dt1[1:], curs.fetchone()):
try:
@@ -92,8 +92,8 @@ for n, x in zip(dt1[1:], curs.fetchone()):
s = repr(n) + "\n -> " + repr(x) + "\n -> " + x.isoformat()
except:
s = repr(n) + "\n -> " + repr(x) + "\n -> " + str(x)
- print s
-print
+ print(s)
+print()
curs.execute("DROP TABLE test_dt")
conn.commit()
diff --git a/examples/encoding.py b/examples/encoding.py
index 77fd871..693a88d 100644
--- a/examples/encoding.py
+++ b/examples/encoding.py
@@ -26,80 +26,80 @@ import psycopg2.extensions
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Initial encoding for this connection is", conn.encoding
+print("Initial encoding for this connection is", conn.encoding)
-print "\n** This example is supposed to be run in a UNICODE terminal! **\n"
+print("\n** This example is supposed to be run in a UNICODE terminal! **\n")
-print "Available encodings:"
+print("Available encodings:")
encs = psycopg2.extensions.encodings.items()
encs.sort()
for a, b in encs:
- print " ", a, "<->", b
+ print(" ", a, "<->", b)
-print "Using STRING typecaster"
-print "Setting backend encoding to LATIN1 and executing queries:"
+print("Using STRING typecaster")
+print("Setting backend encoding to LATIN1 and executing queries:")
conn.set_client_encoding('LATIN1')
curs = conn.cursor()
curs.execute("SELECT %s::TEXT AS foo", ('àèìòù',))
x = curs.fetchone()[0]
-print " ->", unicode(x, 'latin-1').encode('utf-8'), type(x)
+print(" ->", unicode(x, 'latin-1').encode('utf-8'), type(x))
curs.execute("SELECT %s::TEXT AS foo", (u'àèìòù',))
x = curs.fetchone()[0]
-print " ->", unicode(x, 'latin-1').encode('utf-8'), type(x)
+print(" ->", unicode(x, 'latin-1').encode('utf-8'), type(x))
-print "Setting backend encoding to UTF8 and executing queries:"
+print("Setting backend encoding to UTF8 and executing queries:")
conn.set_client_encoding('UNICODE')
curs = conn.cursor()
curs.execute("SELECT %s::TEXT AS foo", (u'àèìòù'.encode('utf-8'),))
x = curs.fetchone()[0]
-print " ->", x, type(x)
+print(" ->", x, type(x))
curs.execute("SELECT %s::TEXT AS foo", (u'àèìòù',))
x = curs.fetchone()[0]
-print " ->", x, type(x)
+print(" ->", x, type(x))
-print "Using UNICODE typecaster"
+print("Using UNICODE typecaster")
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
-print "Setting backend encoding to LATIN1 and executing queries:"
+print("Setting backend encoding to LATIN1 and executing queries:")
conn.set_client_encoding('LATIN1')
curs = conn.cursor()
curs.execute("SELECT %s::TEXT AS foo", ('àèìòù',))
x = curs.fetchone()[0]
-print " ->", x.encode('utf-8'), ":", type(x)
+print(" ->", x.encode('utf-8'), ":", type(x))
curs.execute("SELECT %s::TEXT AS foo", (u'àèìòù',))
x = curs.fetchone()[0]
-print " ->", x.encode('utf-8'), ":", type(x)
+print(" ->", x.encode('utf-8'), ":", type(x))
-print "Setting backend encoding to UTF8 and executing queries:"
+print("Setting backend encoding to UTF8 and executing queries:")
conn.set_client_encoding('UNICODE')
curs = conn.cursor()
curs.execute("SELECT %s::TEXT AS foo", (u'àèìòù'.encode('utf-8'),))
x = curs.fetchone()[0]
-print " ->", x.encode('utf-8'), ":", type(x)
+print(" ->", x.encode('utf-8'), ":", type(x))
curs.execute("SELECT %s::TEXT AS foo", (u'àèìòù',))
x = curs.fetchone()[0]
-print " ->", x.encode('utf-8'), ":", type(x)
+print(" ->", x.encode('utf-8'), ":", type(x))
-print "Executing full UNICODE queries"
+print("Executing full UNICODE queries")
-print "Setting backend encoding to LATIN1 and executing queries:"
+print("Setting backend encoding to LATIN1 and executing queries:")
conn.set_client_encoding('LATIN1')
curs = conn.cursor()
curs.execute(u"SELECT %s::TEXT AS foo", ('àèìòù',))
x = curs.fetchone()[0]
-print " ->", x.encode('utf-8'), ":", type(x)
+print(" ->", x.encode('utf-8'), ":", type(x))
curs.execute(u"SELECT %s::TEXT AS foo", (u'àèìòù',))
x = curs.fetchone()[0]
-print " ->", x.encode('utf-8'), ":", type(x)
+print(" ->", x.encode('utf-8'), ":", type(x))
-print "Setting backend encoding to UTF8 and executing queries:"
+print("Setting backend encoding to UTF8 and executing queries:")
conn.set_client_encoding('UNICODE')
curs = conn.cursor()
curs.execute(u"SELECT %s::TEXT AS foo", (u'àèìòù'.encode('utf-8'),))
x = curs.fetchone()[0]
-print " ->", x.encode('utf-8'), ":", type(x)
+print(" ->", x.encode('utf-8'), ":", type(x))
curs.execute(u"SELECT %s::TEXT AS foo", (u'àèìòù',))
x = curs.fetchone()[0]
-print " ->", x.encode('utf-8'), ":", type(x)
+print(" ->", x.encode('utf-8'), ":", type(x))
diff --git a/examples/fetch.py b/examples/fetch.py
index 096a47e..56b00be 100644
--- a/examples/fetch.py
+++ b/examples/fetch.py
@@ -24,9 +24,9 @@ import psycopg2
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
curs = conn.cursor()
try:
@@ -68,12 +68,12 @@ conn.commit()
ncurs = conn.cursor("crs")
ncurs.execute("SELECT * FROM test_fetch")
-print "First 10 rows:", flatten(ncurs.fetchmany(10))
+print("First 10 rows:", flatten(ncurs.fetchmany(10)))
ncurs.scroll(-5)
-print "Moved back cursor by 5 rows (to row 5.)"
-print "Another 10 rows:", flatten(ncurs.fetchmany(10))
-print "Another one:", list(ncurs.fetchone())
-print "The remaining rows:", flatten(ncurs.fetchall())
+print("Moved back cursor by 5 rows (to row 5.)")
+print("Another 10 rows:", flatten(ncurs.fetchmany(10)))
+print("Another one:", list(ncurs.fetchone()))
+print("The remaining rows:", flatten(ncurs.fetchall()))
conn.rollback()
curs.execute("DROP TABLE test_fetch")
diff --git a/examples/lastrowid.py b/examples/lastrowid.py
index ea5a3b6..da209d6 100644
--- a/examples/lastrowid.py
+++ b/examples/lastrowid.py
@@ -23,7 +23,7 @@ import sys, psycopg2
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
curs = conn.cursor()
@@ -42,18 +42,18 @@ curs.execute("""INSERT INTO test_oid
VALUES (%(name)s, %(surname)s)""", data[0])
foid = curs.lastrowid
-print "Oid for %(name)s %(surname)s" % data[0], "is", foid
+print("Oid for %(name)s %(surname)s" % data[0], "is", foid)
curs.execute("""INSERT INTO test_oid
VALUES (%(name)s, %(surname)s)""", data[1])
moid = curs.lastrowid
-print "Oid for %(name)s %(surname)s" % data[1], "is", moid
+print("Oid for %(name)s %(surname)s" % data[1], "is", moid)
curs.execute("SELECT * FROM test_oid WHERE oid = %s", (foid,))
-print "Oid", foid, "selected %s %s" % curs.fetchone()
+print("Oid", foid, "selected %s %s" % curs.fetchone())
curs.execute("SELECT * FROM test_oid WHERE oid = %s", (moid,))
-print "Oid", moid, "selected %s %s" % curs.fetchone()
+print("Oid", moid, "selected %s %s" % curs.fetchone())
curs.execute("DROP TABLE test_oid")
conn.commit()
diff --git a/examples/lobject.py b/examples/lobject.py
index de18964..242208e 100644
--- a/examples/lobject.py
+++ b/examples/lobject.py
@@ -24,68 +24,68 @@ import psycopg2
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
# this will create a large object with a new random oid, we'll
# use it to make some basic tests about read/write and seek.
lobj = conn.lobject()
loid = lobj.oid
-print "Created a new large object with oid", loid
+print("Created a new large object with oid", loid)
-print "Manually importing some binary data into the object:"
+print("Manually importing some binary data into the object:")
data = open("somehackers.jpg").read()
len = lobj.write(data)
-print " imported", len, "bytes of data"
+print(" imported", len, "bytes of data")
conn.commit()
-print "Trying to (re)open large object with oid", loid
+print("Trying to (re)open large object with oid", loid)
lobj = conn.lobject(loid)
-print "Manually exporting the data from the lobject:"
+print("Manually exporting the data from the lobject:")
data1 = lobj.read()
len = lobj.tell()
lobj.seek(0, 0)
data2 = lobj.read()
if data1 != data2:
- print "ERROR: read after seek returned different data"
+ print("ERROR: read after seek returned different data")
open("somehackers_lobject1.jpg", 'wb').write(data1)
-print " written", len, "bytes of data to somehackers_lobject1.jpg"
+print(" written", len, "bytes of data to somehackers_lobject1.jpg")
lobj.unlink()
-print "Large object with oid", loid, "removed"
+print("Large object with oid", loid, "removed")
conn.commit()
# now we try to use the import and export functions to do the same
lobj = conn.lobject(0, 'n', 0, "somehackers.jpg")
loid = lobj.oid
-print "Imported a new large object with oid", loid
+print("Imported a new large object with oid", loid)
conn.commit()
-print "Trying to (re)open large object with oid", loid
+print("Trying to (re)open large object with oid", loid)
lobj = conn.lobject(loid, 'n')
-print "Using export() to export the data from the large object:"
+print("Using export() to export the data from the large object:")
lobj.export("somehackers_lobject2.jpg")
-print " exported large object to somehackers_lobject2.jpg"
+print(" exported large object to somehackers_lobject2.jpg")
lobj.unlink()
-print "Large object with oid", loid, "removed"
+print("Large object with oid", loid, "removed")
conn.commit()
# this will create a very large object with a new random oid.
lobj = conn.lobject()
loid = lobj.oid
-print "Created a new large object with oid", loid
+print("Created a new large object with oid", loid)
-print "Manually importing a lot of data into the object:"
+print("Manually importing a lot of data into the object:")
data = "data" * 1000000
len = lobj.write(data)
-print " imported", len, "bytes of data"
+print(" imported", len, "bytes of data")
conn.rollback()
-print "\nNow try to load the new images, to check it worked!"
+print("\nNow try to load the new images, to check it worked!")
diff --git a/examples/mogrify.py b/examples/mogrify.py
index 3229fe7..c6e04b5 100644
--- a/examples/mogrify.py
+++ b/examples/mogrify.py
@@ -24,10 +24,10 @@ import sys, psycopg2
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
curs = conn.cursor()
curs.execute("SELECT %(foo)s AS foo", {'foo':'bar'})
@@ -37,11 +37,11 @@ curs.execute("SELECT %(foo)s AS foo", {'foo':42})
curs.execute("SELECT %(foo)s AS foo", {'foo':u'yatt�!'})
curs.execute("SELECT %(foo)s AS foo", {'foo':u'bar'})
-print curs.mogrify("SELECT %(foo)s AS foo", {'foo':'bar'})
-print curs.mogrify("SELECT %(foo)s AS foo", {'foo':None})
-print curs.mogrify("SELECT %(foo)s AS foo", {'foo':True})
-print curs.mogrify("SELECT %(foo)s AS foo", {'foo':42})
-print curs.mogrify("SELECT %(foo)s AS foo", {'foo':u'yatt�!'})
-print curs.mogrify("SELECT %(foo)s AS foo", {'foo':u'bar'})
+print(curs.mogrify("SELECT %(foo)s AS foo", {'foo':'bar'}))
+print(curs.mogrify("SELECT %(foo)s AS foo", {'foo':None}))
+print(curs.mogrify("SELECT %(foo)s AS foo", {'foo':True}))
+print(curs.mogrify("SELECT %(foo)s AS foo", {'foo':42}))
+print(curs.mogrify("SELECT %(foo)s AS foo", {'foo':u'yatt�!'}))
+print(curs.mogrify("SELECT %(foo)s AS foo", {'foo':u'bar'}))
conn.rollback()
diff --git a/examples/myfirstrecipe.py b/examples/myfirstrecipe.py
index e0df879..1390ad0 100644
--- a/examples/myfirstrecipe.py
+++ b/examples/myfirstrecipe.py
@@ -122,5 +122,5 @@ register_adapter(int, AsIs)
# the SQL_IN class by calling psycopg's adapt() directly:
if __name__ == '__main__':
- print "Note how the string will be SQL-quoted, but the number will not:"
- print psycoadapt(("this is an 'sql quoted' str\\ing", 1, 2.0))
+ print("Note how the string will be SQL-quoted, but the number will not:")
+ print(psycoadapt(("this is an 'sql quoted' str\\ing", 1, 2.0)))
diff --git a/examples/notify.py b/examples/notify.py
index ca0dcd2..eb0f2fa 100644
--- a/examples/notify.py
+++ b/examples/notify.py
@@ -26,20 +26,20 @@ from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
curs = conn.cursor()
curs.execute("listen test")
-print "Waiting for 'NOTIFY test'"
+print("Waiting for 'NOTIFY test'")
while 1:
if select.select([conn],[],[],5)==([],[],[]):
- print "Timeout"
+ print("Timeout")
else:
conn.poll()
while conn.notifies:
- print "Got NOTIFY:", conn.notifies.pop()
+ print("Got NOTIFY:", conn.notifies.pop())
diff --git a/examples/simple.py b/examples/simple.py
index 339419e..08191ea 100644
--- a/examples/simple.py
+++ b/examples/simple.py
@@ -30,17 +30,17 @@ import psycopg2
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
curs = conn.cursor()
curs.execute("SELECT 1 AS foo")
-print curs.fetchone()
+print(curs.fetchone())
curs.execute("SELECT 1 AS foo")
-print curs.fetchmany()
+print(curs.fetchmany())
curs.execute("SELECT 1 AS foo")
-print curs.fetchall()
+print(curs.fetchall())
conn.rollback()
diff --git a/examples/threads.py b/examples/threads.py
index e0be7e0..49a495c 100644
--- a/examples/threads.py
+++ b/examples/threads.py
@@ -45,7 +45,7 @@ if len(sys.argv) > 1:
if len(sys.argv) > 2:
MODE = int(sys.argv[2])
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
curs = conn.cursor()
@@ -77,7 +77,7 @@ def insert_func(conn_or_pool, rows):
if MODE == 1:
conn_or_pool.putconn(conn)
s = name + ": COMMIT STEP " + str(i)
- print s
+ print(s)
if MODE == 1:
conn = conn_or_pool.getconn()
c = conn.cursor()
@@ -85,8 +85,8 @@ def insert_func(conn_or_pool, rows):
c.execute("INSERT INTO test_threads VALUES (%s, %s, %s)",
(str(i), i, float(i)))
except psycopg2.ProgrammingError as err:
- print name, ": an error occurred; skipping this insert"
- print err
+ print(name, ": an error occurred; skipping this insert")
+ print(err)
conn.commit()
## a nice select function that prints the current number of rows in the
diff --git a/examples/typecast.py b/examples/typecast.py
index 169f3ac..e6eda6c 100644
--- a/examples/typecast.py
+++ b/examples/typecast.py
@@ -29,14 +29,14 @@ import psycopg2.extensions
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Encoding for this connection is", conn.encoding
+print("Encoding for this connection is", conn.encoding)
curs = conn.cursor()
curs.execute("SELECT 'text'::text AS foo")
textoid = curs.description[0][1]
-print "Oid for the text datatype is", textoid
+print("Oid for the text datatype is", textoid)
def castA(s, curs):
if s is not None: return "(A) " + s
@@ -48,18 +48,18 @@ TYPEB = psycopg2.extensions.new_type((textoid,), "TYPEB", castB)
curs = conn.cursor()
curs.execute("SELECT 'some text.'::text AS foo")
-print "Some text from plain connection:", curs.fetchone()[0]
+print("Some text from plain connection:", curs.fetchone()[0])
psycopg2.extensions.register_type(TYPEA, conn)
curs = conn.cursor()
curs.execute("SELECT 'some text.'::text AS foo")
-print "Some text from connection with typecaster:", curs.fetchone()[0]
+print("Some text from connection with typecaster:", curs.fetchone()[0])
curs = conn.cursor()
psycopg2.extensions.register_type(TYPEB, curs)
curs.execute("SELECT 'some text.'::text AS foo")
-print "Some text from cursor with typecaster:", curs.fetchone()[0]
+print("Some text from cursor with typecaster:", curs.fetchone()[0])
curs = conn.cursor()
curs.execute("SELECT 'some text.'::text AS foo")
-print "Some text from connection with typecaster again:", curs.fetchone()[0]
+print("Some text from connection with typecaster again:", curs.fetchone()[0])
diff --git a/examples/tz.py b/examples/tz.py
index c3dd8e4..1726a6c 100644
--- a/examples/tz.py
+++ b/examples/tz.py
@@ -28,7 +28,7 @@ from psycopg2.tz import ZERO, LOCAL, FixedOffsetTimezone
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
curs = conn.cursor()
@@ -42,27 +42,27 @@ conn.commit()
d = datetime.datetime(1971, 10, 19, 22, 30, 0, tzinfo=LOCAL)
curs.execute("INSERT INTO test_tz VALUES (%s)", (d,))
-print "Inserted timestamp with timezone:", d
-print "Time zone:", d.tzinfo.tzname(d), "offset:", d.tzinfo.utcoffset(d)
+print("Inserted timestamp with timezone:", d)
+print("Time zone:", d.tzinfo.tzname(d), "offset:", d.tzinfo.utcoffset(d))
tz = FixedOffsetTimezone(-5*60, "EST")
d = datetime.datetime(1971, 10, 19, 22, 30, 0, tzinfo=tz)
curs.execute("INSERT INTO test_tz VALUES (%s)", (d,))
-print "Inserted timestamp with timezone:", d
-print "Time zone:", d.tzinfo.tzname(d), "offset:", d.tzinfo.utcoffset(d)
+print("Inserted timestamp with timezone:", d)
+print("Time zone:", d.tzinfo.tzname(d), "offset:", d.tzinfo.utcoffset(d))
curs.execute("SELECT * FROM test_tz")
d = curs.fetchone()[0]
curs.execute("INSERT INTO test_tz VALUES (%s)", (d,))
-print "Inserted SELECTed timestamp:", d
-print "Time zone:", d.tzinfo.tzname(d), "offset:", d.tzinfo.utcoffset(d)
+print("Inserted SELECTed timestamp:", d)
+print("Time zone:", d.tzinfo.tzname(d), "offset:", d.tzinfo.utcoffset(d))
curs.execute("SELECT * FROM test_tz")
for d in curs:
u = d[0].utcoffset() or ZERO
- print "UTC time: ", d[0] - u
- print "Local time:", d[0]
- print "Time zone:", d[0].tzinfo.tzname(d[0]), d[0].tzinfo.utcoffset(d[0])
+ print("UTC time: ", d[0] - u)
+ print("Local time:", d[0])
+ print("Time zone:", d[0].tzinfo.tzname(d[0]), d[0].tzinfo.utcoffset(d[0]))
curs.execute("DROP TABLE test_tz")
diff --git a/examples/usercast.py b/examples/usercast.py
index 26a5c16..b905042 100644
--- a/examples/usercast.py
+++ b/examples/usercast.py
@@ -33,9 +33,9 @@ import psycopg2.extras
if len(sys.argv) > 1:
DSN = sys.argv[1]
-print "Opening connection using dsn:", DSN
+print("Opening connection using dsn:", DSN)
conn = psycopg2.connect(DSN)
-print "Initial encoding for this connection is", conn.encoding
+print("Initial encoding for this connection is", conn.encoding)
curs = conn.cursor()
try:
@@ -98,7 +98,7 @@ class Rect(object):
# here we select from the empty table, just to grab the description
curs.execute("SELECT b FROM test_cast WHERE 0=1")
boxoid = curs.description[0][1]
-print "Oid for the box datatype is", boxoid
+print("Oid for the box datatype is", boxoid)
# and build the user cast object
BOX = psycopg2.extensions.new_type((boxoid,), "BOX", Rect)
@@ -113,14 +113,14 @@ for i in range(100):
whrandom.randint(0,100), whrandom.randint(0,100))
curs.execute("INSERT INTO test_cast VALUES ('%(p1)s', '%(p2)s', %(box)s)",
{'box':b, 'p1':p1, 'p2':p2})
-print "Added 100 boxed to the database"
+print("Added 100 boxed to the database")
# select and print all boxes with at least one point inside
curs.execute("SELECT b FROM test_cast WHERE p1 @ b OR p2 @ b")
boxes = curs.fetchall()
-print "Found %d boxes with at least a point inside:" % len(boxes)
+print("Found %d boxes with at least a point inside:" % len(boxes))
for box in boxes:
- print " ", box[0].show()
+ print(" ", box[0].show())
curs.execute("DROP TABLE test_cast")
conn.commit()