~groldster/ubuntu/maverick/psycopg2/merge-611040

« back to all changes in this revision

Viewing changes to examples/lastrowid.py

  • Committer: Bazaar Package Importer
  • Author(s): Fabio Tranchitella
  • Date: 2006-08-09 10:28:30 UTC
  • Revision ID: james.westby@ubuntu.com-20060809102830-grac1dsp24uyqfp4
Tags: upstream-2.0.4
ImportĀ upstreamĀ versionĀ 2.0.4

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# lastrowid.py -  example of using .lastrowid attribute
 
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, psycopg2
 
22
 
 
23
if len(sys.argv) > 1:
 
24
    DSN = sys.argv[1]
 
25
 
 
26
print "Opening connection using dns:", DSN
 
27
conn = psycopg2.connect(DSN)
 
28
curs = conn.cursor()
 
29
 
 
30
try:
 
31
    curs.execute("CREATE TABLE test_oid (name text, surname text)")
 
32
except:
 
33
    conn.rollback()
 
34
    curs.execute("DROP TABLE test_oid")
 
35
    curs.execute("CREATE TABLE test_oid (name text, surname text)")
 
36
conn.commit()
 
37
 
 
38
data = ({'name':'Federico', 'surname':'Di Gregorio'},
 
39
        {'name':'Pierluigi', 'surname':'Di Nunzio'})
 
40
 
 
41
curs.execute("""INSERT INTO test_oid
 
42
                VALUES (%(name)s, %(surname)s)""", data[0])
 
43
 
 
44
foid = curs.lastrowid
 
45
print "Oid for %(name)s %(surname)s" % data[0], "is", foid
 
46
 
 
47
curs.execute("""INSERT INTO test_oid
 
48
                VALUES (%(name)s, %(surname)s)""", data[1])
 
49
moid = curs.lastrowid
 
50
print "Oid for %(name)s %(surname)s" % data[1], "is", moid
 
51
 
 
52
curs.execute("SELECT * FROM test_oid WHERE oid = %s", (foid,))
 
53
print "Oid", foid, "selected %s %s" % curs.fetchone()
 
54
 
 
55
curs.execute("SELECT * FROM test_oid WHERE oid = %s", (moid,))
 
56
print "Oid", moid, "selected %s %s" % curs.fetchone()
 
57
 
 
58
curs.execute("DROP TABLE test_oid")
 
59
conn.commit()