Skip to content

Commit 3243261

Browse files
Added samples that were originally created for Open World 2016.
1 parent 340dcb7 commit 3243261

File tree

12 files changed

+520
-0
lines changed

12 files changed

+520
-0
lines changed

‎samples/ArrayDMLRowCounts.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# ArrayDMLRowCounts.py
7+
#
8+
# Demonstrate the use of the 12.1 feature that allows cursor.executemany()
9+
# to return the number of rows affected by each individual execution as a list.
10+
# The parameter "arraydmlrowcounts" must be set to True in the call to
11+
# cursor.executemany() after which cursor.getarraydmlrowcounts() can be called.
12+
#
13+
# This script requires cx_Oracle 5.2 and higher.
14+
#------------------------------------------------------------------------------
15+
16+
from __future__ import print_function
17+
18+
import cx_Oracle
19+
import SampleEnv
20+
21+
connection = cx_Oracle.Connection(SampleEnv.MAIN_CONNECT_STRING)
22+
cursor = connection.cursor()
23+
24+
# show the number of rows for each parent ID as a means of verifying the
25+
# output from the delete statement
26+
for parentId, count in cursor.execute("""
27+
select ParentId, count(*)
28+
from ChildTable
29+
group by ParentId
30+
order by ParentId"""):
31+
print("Parent ID:", parentId, "has", int(count), "rows.")
32+
print()
33+
34+
# delete the following parent IDs only
35+
parentIdsToDelete = [2, 3, 5]
36+
37+
print("Deleting Parent IDs:", parentIdsToDelete)
38+
print()
39+
40+
# enable array DML row counts for each iteration executed in executemany()
41+
cursor.executemany("""
42+
delete from ChildTable
43+
where ParentId = :1""",
44+
[(i,) for i in parentIdsToDelete],
45+
arraydmlrowcounts = True)
46+
47+
# display the number of rows deleted for each parent ID
48+
rowCounts = cursor.getarraydmlrowcounts()
49+
for parentId, count in zip(parentIdsToDelete, rowCounts):
50+
print("Parent ID:", parentId, "deleted", count, "rows.")
51+

‎samples/BatchErrors.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# BatchErrors.py
7+
#
8+
# Demonstrate the use of the Oracle Database 12.1 feature that allows
9+
# cursor.executemany() to complete successfully, even if errors take
10+
# place during the execution of one or more of the individual
11+
# executions. The parameter "batcherrors" must be set to True in the
12+
# call to cursor.executemany() after which cursor.getbatcherrors() can
13+
# be called, which will return a list of error objects.
14+
#
15+
# This script requires cx_Oracle 5.2 and higher.
16+
#------------------------------------------------------------------------------
17+
18+
from __future__ import print_function
19+
20+
import cx_Oracle
21+
import SampleEnv
22+
23+
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
24+
cursor = connection.cursor()
25+
26+
# define data to insert
27+
dataToInsert = [
28+
(1016, 1, 'Child 2 of Parent 1'),
29+
(1017, 1, 'Child 3 of Parent 1'),
30+
(1018, 2, 'Child 4 of Parent 2'),
31+
(1018, 2, 'Child 4 of Parent 2'), # duplicate key
32+
(1019, 3, 'Child 3 of Parent 3'),
33+
(1020, 3, 'Child 4 of Parent 4'),
34+
(1021, 6, 'Child 1 of Parent 6'), # parent does not exist
35+
(1022, 4, 'Child 6 of Parent 4'),
36+
]
37+
38+
# retrieve the number of rows in the table
39+
cursor.execute("""
40+
select count(*)
41+
from ChildTable""")
42+
count, = cursor.fetchone()
43+
print("number of rows in child table:", int(count))
44+
print("number of rows to insert:", len(dataToInsert))
45+
46+
# old method: executemany() with data errors results in stoppage after the
47+
# first error takes place; the row count is updated to show how many rows
48+
# actually succeeded
49+
try:
50+
cursor.executemany("insert into ChildTable values (:1, :2, :3)",
51+
dataToInsert)
52+
except cx_Oracle.DatabaseError as e:
53+
error, = e.args
54+
print("FAILED with error:", error.message)
55+
print("number of rows which succeeded:", cursor.rowcount)
56+
57+
# demonstrate that the row count is accurate
58+
cursor.execute("""
59+
select count(*)
60+
from ChildTable""")
61+
count, = cursor.fetchone()
62+
print("number of rows in child table after failed insert:", int(count))
63+
64+
# roll back so we can perform the same work using the new method
65+
connection.rollback()
66+
67+
# new method: executemany() with batch errors enabled (and array DML row counts
68+
# also enabled) results in no immediate error being raised
69+
cursor.executemany("insert into ChildTable values (:1, :2, :3)", dataToInsert,
70+
batcherrors = True, arraydmlrowcounts = True)
71+
72+
# where errors have taken place, the row count is 0; otherwise it is 1
73+
rowCounts = cursor.getarraydmlrowcounts()
74+
print("Array DML row counts:", rowCounts)
75+
76+
# display the errors that have taken place
77+
errors = cursor.getbatcherrors()
78+
print("number of errors which took place:", len(errors))
79+
for error in errors:
80+
print("Error", error.message.rstrip(), "at row offset", error.offset)
81+
82+
# demonstrate that all of the rows without errors have been successfully
83+
# inserted
84+
cursor.execute("""
85+
select count(*)
86+
from ChildTable""")
87+
count, = cursor.fetchone()
88+
print("number of rows in child table after successful insert:", int(count))

‎samples/BindInsert.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# BindInsert.py
7+
#
8+
# Demonstrate how to insert a row into a table using bind variables.
9+
#------------------------------------------------------------------------------
10+
11+
from __future__ import print_function
12+
13+
import cx_Oracle
14+
import SampleEnv
15+
16+
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
17+
18+
rows = [ (1, "First" ),
19+
(2, "Second" ),
20+
(3, "Third" ),
21+
(4, "Fourth" ),
22+
(5, "Fifth" ),
23+
(6, "Sixth" ),
24+
(7, "Seventh" ) ]
25+
26+
cursor = connection.cursor()
27+
cursor.executemany("insert into mytab(id, data) values (:1, :2)", rows)
28+
29+
# Don't commit - this lets us run the demo multiple times
30+
#connection.commit()
31+
32+
# Now query the results back
33+
34+
for row in cursor.execute('select * from mytab'):
35+
print(row)
36+

‎samples/BindQuery.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# BindQuery.py
7+
#
8+
# Demonstrate how to perform a simple query limiting the rows retrieved using
9+
# a bind variable. Since the query that is executed is identical, no additional
10+
# parsing is required, thereby reducing overhead and increasing performance. It
11+
# also permits data to be bound without having to be concerned about escaping
12+
# special characters or SQL injection attacks.
13+
#------------------------------------------------------------------------------
14+
15+
from __future__ import print_function
16+
17+
import cx_Oracle
18+
import SampleEnv
19+
20+
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
21+
22+
cursor = connection.cursor()
23+
sql = 'select * from SampleQueryTab where id = :bvid'
24+
25+
print("Query results with id = 4")
26+
for row in cursor.execute(sql, bvid = 4):
27+
print(row)
28+
print()
29+
30+
print("Query results with id = 1")
31+
for row in cursor.execute(sql, bvid = 1):
32+
print(row)
33+
print()
34+

‎samples/GenericRowFactory.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# GenericRowFactory.py
7+
#
8+
# Demonstrate the ability to return named tuples for all queries using a
9+
# subclassed cursor and row factory.
10+
#------------------------------------------------------------------------------
11+
12+
from __future__ import print_function
13+
14+
import collections
15+
import cx_Oracle
16+
import SampleEnv
17+
18+
class Connection(cx_Oracle.Connection):
19+
20+
def cursor(self):
21+
return Cursor(self)
22+
23+
24+
class Cursor(cx_Oracle.Cursor):
25+
26+
def execute(self, statement, args = None):
27+
prepareNeeded = (self.statement != statement)
28+
result = super(Cursor, self).execute(statement, args or [])
29+
if prepareNeeded:
30+
description = self.description
31+
if description:
32+
names = [d[0] for d in description]
33+
self.rowfactory = collections.namedtuple("GenericQuery", names)
34+
return result
35+
36+
37+
# create new subclassed connection and cursor
38+
connection = Connection(SampleEnv.MAIN_CONNECT_STRING)
39+
cursor = connection.cursor()
40+
41+
# the names are now available directly for each query executed
42+
for row in cursor.execute("select ParentId, Description from ParentTable"):
43+
print(row.PARENTID, "->", row.DESCRIPTION)
44+
print()
45+
46+
for row in cursor.execute("select ChildId, Description from ChildTable"):
47+
print(row.CHILDID, "->", row.DESCRIPTION)
48+
print()
49+

‎samples/PLSQLCollection.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# PLSQLCollection.py
7+
#
8+
# Demonstrate how to get the value of a PL/SQL collection from a stored
9+
# procedure.
10+
#
11+
# This feature is new in cx_Oracle 5.3 and is only available in Oracle
12+
# Database 12.1 and higher.
13+
#------------------------------------------------------------------------------
14+
15+
from __future__ import print_function
16+
17+
import cx_Oracle
18+
import SampleEnv
19+
20+
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
21+
22+
# create new empty object of the correct type
23+
# note the use of a PL/SQL type defined in a package
24+
typeObj = connection.gettype("PKG_DEMO.UDT_STRINGLIST")
25+
obj = typeObj.newobject()
26+
27+
# call the stored procedure which will populate the object
28+
cursor = connection.cursor()
29+
cursor.callproc("pkg_Demo.DemoCollectionOut", (obj,))
30+
31+
# show the indexes that are used by the collection
32+
print("Indexes and values of collection:")
33+
ix = obj.first()
34+
while ix is not None:
35+
print(ix, "->", obj.getelement(ix))
36+
ix = obj.next(ix)
37+
print()
38+
39+
# show the values as a simple list
40+
print("Values of collection as list:")
41+
print(obj.aslist())
42+

‎samples/PLSQLFunction.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# PLSQLFunction.py
7+
#
8+
# Demonstrate how to call a PL/SQL function and get its return value.
9+
#------------------------------------------------------------------------------
10+
11+
from __future__ import print_function
12+
13+
import cx_Oracle
14+
import SampleEnv
15+
16+
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
17+
18+
cursor = connection.cursor()
19+
res = cursor.callfunc('myfunc', int, ('abc', 2))
20+
print(res)
21+

‎samples/PLSQLProcedure.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#------------------------------------------------------------------------------
2+
# Copyright 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3+
#------------------------------------------------------------------------------
4+
5+
#------------------------------------------------------------------------------
6+
# PLSQLProcedure.py
7+
#
8+
# Demonstrate how to call a PL/SQL stored procedure and get the results of an
9+
# OUT variable.
10+
#------------------------------------------------------------------------------
11+
12+
from __future__ import print_function
13+
14+
import cx_Oracle
15+
import SampleEnv
16+
17+
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
18+
19+
cursor = connection.cursor()
20+
myvar = cursor.var(int)
21+
cursor.callproc('myproc', (123, myvar))
22+
print(myvar.getvalue())
23+

0 commit comments

Comments
 (0)