1 # copy_to.py -- example about copy_to
3 # Copyright (C) 2002 Tom Jenkins <tjenkins@devis.com>
4 # Copyright (C) 2005 Federico Di Gregorio <fog@initd.org>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by the
8 # Free Software Foundation; either version 2, or (at your option) any later
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
13 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 ## put in DSN your DSN string
21 ## don't modify anything below tis line (except for experimenting)
31 print "Opening connection using dns:", DSN
32 conn = psycopg2.connect(DSN)
33 print "Encoding for this connection is", conn.encoding
37 curs.execute("CREATE TABLE test_copy (fld1 text, fld2 text, fld3 int4)")
40 curs.execute("DROP TABLE test_copy")
41 curs.execute("CREATE TABLE test_copy (fld1 text, fld2 text, fld3 int4)")
44 # demostrate copy_to functionality
45 data = [('Tom', 'Jenkins', '37'),
46 ('Madonna', None, '45'),
47 ('Federico', 'Di Gregorio', None)]
48 query = "INSERT INTO test_copy VALUES (%s, %s, %s)"
49 curs.executemany(query, data)
52 # copy_to using defaults
53 io = open('copy_to.txt', 'w')
54 curs.copy_to(io, 'test_copy')
55 print "1) Copy %d records into file object using defaults: " % len (data) + \
56 "sep = \\t and null = \\N"
59 rows = open('copy_to.txt', 'r').readlines()
60 print " File has %d rows:" % len(rows)
65 # copy_to using custom separator
66 io = open('copy_to.txt', 'w')
67 curs.copy_to(io, 'test_copy', ':')
68 print "2) Copy %d records into file object using sep = :" % len(data)
71 rows = open('copy_to.txt', 'r').readlines()
72 print " File has %d rows:" % len(rows)
77 # copy_to using custom null identifier
78 io = open('copy_to.txt', 'w')
79 curs.copy_to(io, 'test_copy', null='NULL')
80 print "3) Copy %d records into file object using null = NULL" % len(data)
83 rows = open('copy_to.txt', 'r').readlines()
84 print " File has %d rows:" % len(rows)
89 # copy_to using custom separator and null identifier
90 io = open('copy_to.txt', 'w')
91 curs.copy_to(io, 'test_copy', ':', 'NULL')
92 print "4) Copy %d records into file object using sep = : and null ) NULL" % \
96 rows = open('copy_to.txt', 'r').readlines()
97 print " File has %d rows:" % len(rows)
102 curs.execute("DROP TABLE test_copy")
103 os.unlink('copy_to.txt')