|
| 1 | +#------------------------------------------------------------------------------ |
| 2 | +# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. |
| 3 | +#------------------------------------------------------------------------------ |
| 4 | + |
| 5 | +#------------------------------------------------------------------------------ |
| 6 | +# LastRowid.py |
| 7 | +# Demonstrates the use of the cursor.lastrowid attribute. |
| 8 | +# |
| 9 | +# This script requires cx_Oracle 7.3 and higher. |
| 10 | +#------------------------------------------------------------------------------ |
| 11 | + |
| 12 | +from __future__ import print_function |
| 13 | + |
| 14 | +import cx_Oracle |
| 15 | +import SampleEnv |
| 16 | + |
| 17 | +connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) |
| 18 | + |
| 19 | +row1 = [1, "First"] |
| 20 | +row2 = [2, "Second"] |
| 21 | + |
| 22 | +# insert a couple of rows and retain the rowid of each |
| 23 | +cursor = connection.cursor() |
| 24 | +cursor.execute("insert into mytab (id, data) values (:1, :2)", row1) |
| 25 | +rowid1 = cursor.lastrowid |
| 26 | +print("Row 1:", row1) |
| 27 | +print("Rowid 1:", rowid1) |
| 28 | +print() |
| 29 | + |
| 30 | +cursor.execute("insert into mytab (id, data) values (:1, :2)", row2) |
| 31 | +rowid2 = cursor.lastrowid |
| 32 | +print("Row 2:", row2) |
| 33 | +print("Rowid 2:", rowid2) |
| 34 | +print() |
| 35 | + |
| 36 | +# the row can be fetched with the rowid that was retained |
| 37 | +cursor.execute("select id, data from mytab where rowid = :1", [rowid1]) |
| 38 | +print("Row 1:", cursor.fetchone()) |
| 39 | +cursor.execute("select id, data from mytab where rowid = :1", [rowid2]) |
| 40 | +print("Row 2:", cursor.fetchone()) |
| 41 | +print() |
| 42 | + |
| 43 | +# updating multiple rows only returns the rowid of the last updated row |
| 44 | +cursor.execute("update mytab set data = data || ' (Modified)'") |
| 45 | +cursor.execute("select id, data from mytab where rowid = :1", |
| 46 | + [cursor.lastrowid]) |
| 47 | +print("Last updated row:", cursor.fetchone()) |
| 48 | + |
| 49 | +# deleting multiple rows only returns the rowid of the last deleted row |
| 50 | +cursor.execute("delete from mytab") |
| 51 | +print("Rowid of last deleted row:", cursor.lastrowid) |
| 52 | + |
| 53 | +# deleting no rows results in a value of None |
| 54 | +cursor.execute("delete from mytab") |
| 55 | +print("Rowid when no rows are deleted:", cursor.lastrowid) |
| 56 | + |
| 57 | +# Don't commit - this lets us run the demo multiple times |
| 58 | +#connection.commit() |
0 commit comments