Skip to content

Commit e2485af

Browse files
Improvement to samples.
1 parent 74a2616 commit e2485af

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+1590
-939
lines changed

doc/src/release_notes.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ oracledb 1.0.1 (TBD)
3232
fetched as floats when oracledb.defaults.fetch_lobs was set to `False`.
3333
#) Thin: ensure that errors that occur during fetch are detected consistently.
3434
#) Thin: fixed issue when fetching null values in implicit results.
35+
#) Improved samples and documentation.
3536

3637

3738
oracledb 1.0.0 (May 2022)

samples/app_context.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,18 +41,23 @@
4141
# this script is currently only supported in python-oracledb thick mode
4242
oracledb.init_oracle_client(lib_dir=sample_env.get_oracle_client())
4343

44-
# define constants used throughout the script; adjust as desired
44+
# client context attributes to be set
4545
APP_CTX_NAMESPACE = "CLIENTCONTEXT"
4646
APP_CTX_ENTRIES = [
4747
( APP_CTX_NAMESPACE, "ATTR1", "VALUE1" ),
4848
( APP_CTX_NAMESPACE, "ATTR2", "VALUE2" ),
4949
( APP_CTX_NAMESPACE, "ATTR3", "VALUE3" )
5050
]
5151

52-
connection = oracledb.connect(sample_env.get_main_connect_string(),
52+
connection = oracledb.connect(user=sample_env.get_main_user(),
53+
password=sample_env.get_main_password(),
54+
dsn=sample_env.get_connect_string(),
5355
appcontext=APP_CTX_ENTRIES)
54-
cursor = connection.cursor()
55-
for namespace, name, value in APP_CTX_ENTRIES:
56-
cursor.execute("select sys_context(:1, :2) from dual", (namespace, name))
57-
value, = cursor.fetchone()
58-
print("Value of context key", name, "is", value)
56+
57+
with connection.cursor() as cursor:
58+
59+
for namespace, name, value in APP_CTX_ENTRIES:
60+
cursor.execute("select sys_context(:1, :2) from dual",
61+
(namespace, name))
62+
value, = cursor.fetchone()
63+
print("Value of context key", name, "is", value)

samples/aq_notification.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,8 @@
2626
# aq_notification.py
2727
#
2828
# Demonstrates using advanced queuing notification. Once this script is
29-
# running, use another session to enqueue a few messages to the
30-
# "DEMO_BOOK_QUEUE" queue. This is most easily accomplished by running the
31-
# object_aq.py sample.
29+
# running, run object_aq.py in another terminal to to enqueue a few messages to
30+
# the "DEMO_BOOK_QUEUE" queue.
3231
#------------------------------------------------------------------------------
3332

3433
import time
@@ -51,8 +50,11 @@ def process_messages(message):
5150
print("Queue name:", message.queue_name)
5251
print("Consumer name:", message.consumer_name)
5352

54-
connection = oracledb.connect(sample_env.get_main_connect_string(),
53+
connection = oracledb.connect(user=sample_env.get_main_user(),
54+
password=sample_env.get_main_password(),
55+
dsn=sample_env.get_connect_string(),
5556
events=True)
57+
5658
sub = connection.subscribe(namespace=oracledb.SUBSCR_NAMESPACE_AQ,
5759
name="DEMO_BOOK_QUEUE", callback=process_messages,
5860
timeout=300)

samples/array_dml_rowcounts.py

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -38,33 +38,36 @@
3838
if not sample_env.get_is_thin():
3939
oracledb.init_oracle_client(lib_dir=sample_env.get_oracle_client())
4040

41-
connection = oracledb.connect(sample_env.get_main_connect_string())
42-
cursor = connection.cursor()
41+
connection = oracledb.connect(user=sample_env.get_main_user(),
42+
password=sample_env.get_main_password(),
43+
dsn=sample_env.get_connect_string())
4344

44-
# show the number of rows for each parent ID as a means of verifying the
45-
# output from the delete statement
46-
for parent_id, count in cursor.execute("""
47-
select ParentId, count(*)
48-
from ChildTable
49-
group by ParentId
50-
order by ParentId"""):
51-
print("Parent ID:", parent_id, "has", int(count), "rows.")
52-
print()
45+
with connection.cursor() as cursor:
5346

54-
# delete the following parent IDs only
55-
parent_ids_to_delete = [20, 30, 50]
47+
# show the number of rows for each parent ID as a means of verifying the
48+
# output from the delete statement
49+
for parent_id, count in cursor.execute("""
50+
select ParentId, count(*)
51+
from ChildTable
52+
group by ParentId
53+
order by ParentId"""):
54+
print("Parent ID:", parent_id, "has", int(count), "rows.")
55+
print()
5656

57-
print("Deleting Parent IDs:", parent_ids_to_delete)
58-
print()
57+
# delete the following parent IDs only
58+
parent_ids_to_delete = [20, 30, 50]
5959

60-
# enable array DML row counts for each iteration executed in executemany()
61-
cursor.executemany("""
62-
delete from ChildTable
63-
where ParentId = :1""",
64-
[(i,) for i in parent_ids_to_delete],
65-
arraydmlrowcounts = True)
60+
print("Deleting Parent IDs:", parent_ids_to_delete)
61+
print()
6662

67-
# display the number of rows deleted for each parent ID
68-
row_counts = cursor.getarraydmlrowcounts()
69-
for parent_id, count in zip(parent_ids_to_delete, row_counts):
70-
print("Parent ID:", parent_id, "deleted", count, "rows.")
63+
# enable array DML row counts for each iteration executed in executemany()
64+
cursor.executemany("""
65+
delete from ChildTable
66+
where ParentId = :1""",
67+
[(i,) for i in parent_ids_to_delete],
68+
arraydmlrowcounts = True)
69+
70+
# display the number of rows deleted for each parent ID
71+
row_counts = cursor.getarraydmlrowcounts()
72+
for parent_id, count in zip(parent_ids_to_delete, row_counts):
73+
print("Parent ID:", parent_id, "deleted", count, "rows.")

samples/batch_errors.py

Lines changed: 63 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -40,69 +40,75 @@
4040
if not sample_env.get_is_thin():
4141
oracledb.init_oracle_client(lib_dir=sample_env.get_oracle_client())
4242

43-
connection = oracledb.connect(sample_env.get_main_connect_string())
44-
cursor = connection.cursor()
43+
connection = oracledb.connect(user=sample_env.get_main_user(),
44+
password=sample_env.get_main_password(),
45+
dsn=sample_env.get_connect_string())
4546

46-
# define data to insert
47-
data_to_insert = [
48-
(1016, 10, 'Child B of Parent 10'),
49-
(1017, 10, 'Child C of Parent 10'),
50-
(1018, 20, 'Child D of Parent 20'),
51-
(1018, 20, 'Child D of Parent 20'), # duplicate key
52-
(1019, 30, 'Child C of Parent 30'),
53-
(1020, 30, 'Child D of Parent 40'),
54-
(1021, 60, 'Child A of Parent 60'), # parent does not exist
55-
(1022, 40, 'Child F of Parent 40'),
56-
]
47+
with connection.cursor() as cursor:
5748

58-
# retrieve the number of rows in the table
59-
cursor.execute("""
60-
select count(*)
61-
from ChildTable""")
62-
count, = cursor.fetchone()
63-
print("number of rows in child table:", int(count))
64-
print("number of rows to insert:", len(data_to_insert))
49+
# retrieve the number of rows in the table
50+
cursor.execute("""
51+
select count(*)
52+
from ChildTable""")
53+
count, = cursor.fetchone()
54+
print("Number of rows in child table:", int(count))
6555

66-
# old method: executemany() with data errors results in stoppage after the
67-
# first error takes place; the row count is updated to show how many rows
68-
# actually succeeded
69-
try:
70-
cursor.executemany("insert into ChildTable values (:1, :2, :3)",
71-
data_to_insert)
72-
except oracledb.DatabaseError as e:
73-
error, = e.args
74-
print("FAILED with error:", error.message)
75-
print("number of rows which succeeded:", cursor.rowcount)
56+
# define data to insert
57+
data_to_insert = [
58+
(1016, 10, 'Child B of Parent 10'),
59+
(1017, 10, 'Child C of Parent 10'),
60+
(1018, 20, 'Child D of Parent 20'),
61+
(1018, 20, 'Child D of Parent 20'), # duplicate key
62+
(1019, 30, 'Child C of Parent 30'),
63+
(1020, 30, 'Child D of Parent 40'),
64+
(1021, 60, 'Child A of Parent 60'), # parent does not exist
65+
(1022, 40, 'Child F of Parent 40'),
66+
]
67+
print("Number of rows to insert:", len(data_to_insert))
68+
69+
# old method: executemany() with data errors results in stoppage after the
70+
# first error takes place; the row count is updated to show how many rows
71+
# actually succeeded
72+
try:
73+
cursor.executemany("insert into ChildTable values (:1, :2, :3)",
74+
data_to_insert)
75+
except oracledb.DatabaseError as e:
76+
error, = e.args
77+
print("Failure with error:", error.message)
78+
print("Number of rows successfully inserted:", cursor.rowcount)
7679

77-
# demonstrate that the row count is accurate
78-
cursor.execute("""
79-
select count(*)
80-
from ChildTable""")
81-
count, = cursor.fetchone()
82-
print("number of rows in child table after failed insert:", int(count))
80+
# demonstrate that the row count is accurate
81+
cursor.execute("""
82+
select count(*)
83+
from ChildTable""")
84+
count, = cursor.fetchone()
85+
print("Number of rows in child table after failed insert:", int(count))
8386

84-
# roll back so we can perform the same work using the new method
85-
connection.rollback()
87+
# roll back so we can perform the same work using the new method
88+
connection.rollback()
8689

87-
# new method: executemany() with batch errors enabled (and array DML row counts
88-
# also enabled) results in no immediate error being raised
89-
cursor.executemany("insert into ChildTable values (:1, :2, :3)",
90-
data_to_insert, batcherrors=True, arraydmlrowcounts=True)
90+
# new method: executemany() with batch errors enabled (and array DML row
91+
# counts also enabled) results in no immediate error being raised
92+
cursor.executemany("insert into ChildTable values (:1, :2, :3)",
93+
data_to_insert, batcherrors=True,
94+
arraydmlrowcounts=True)
9195

92-
# where errors have taken place, the row count is 0; otherwise it is 1
93-
row_counts = cursor.getarraydmlrowcounts()
94-
print("Array DML row counts:", row_counts)
96+
# display the errors that have taken place
97+
errors = cursor.getbatcherrors()
98+
print("Number of rows with bad values:", len(errors))
99+
for error in errors:
100+
print("Error", error.message.rstrip(), "at row offset", error.offset)
95101

96-
# display the errors that have taken place
97-
errors = cursor.getbatcherrors()
98-
print("number of errors which took place:", len(errors))
99-
for error in errors:
100-
print("Error", error.message.rstrip(), "at row offset", error.offset)
102+
# arraydmlrowcounts also shows rows with invalid data: they have a row
103+
# count of 0; otherwise 1 is shown
104+
row_counts = cursor.getarraydmlrowcounts()
105+
print("Array DML row counts:", row_counts)
101106

102-
# demonstrate that all of the rows without errors have been successfully
103-
# inserted
104-
cursor.execute("""
105-
select count(*)
106-
from ChildTable""")
107-
count, = cursor.fetchone()
108-
print("number of rows in child table after successful insert:", int(count))
107+
# demonstrate that all of the rows without errors have been successfully
108+
# inserted
109+
cursor.execute("""
110+
select count(*)
111+
from ChildTable""")
112+
count, = cursor.fetchone()
113+
print("Number of rows in child table after insert with batcherrors "
114+
"enabled:", int(count))

samples/bind_insert.py

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
#------------------------------------------------------------------------------
2626
# bind_insert.py
2727
#
28-
# Demonstrates how to insert a row into a table using bind variables.
28+
# Demonstrates how to insert rows into a table using bind variables.
2929
#------------------------------------------------------------------------------
3030

3131
import oracledb
@@ -35,7 +35,9 @@
3535
if not sample_env.get_is_thin():
3636
oracledb.init_oracle_client(lib_dir=sample_env.get_oracle_client())
3737

38-
connection = oracledb.connect(sample_env.get_main_connect_string())
38+
connection = oracledb.connect(user=sample_env.get_main_user(),
39+
password=sample_env.get_main_password(),
40+
dsn=sample_env.get_connect_string())
3941

4042
#------------------------------------------------------------------------------
4143
# "Bind by position"
@@ -51,13 +53,14 @@
5153
(7, "Seventh")
5254
]
5355

54-
cursor = connection.cursor()
56+
with connection.cursor() as cursor:
5557

56-
# predefine maximum string size to avoid data scans and memory reallocations;
57-
# the None value indicates that the default processing can take place
58-
cursor.setinputsizes(None, 20)
58+
# predefine the maximum string size to avoid data scans and memory
59+
# reallocations. The value 'None' indicates that the default processing
60+
# can take place
61+
cursor.setinputsizes(None, 20)
5962

60-
cursor.executemany("insert into mytab(id, data) values (:1, :2)", rows)
63+
cursor.executemany("insert into mytab(id, data) values (:1, :2)", rows)
6164

6265
#------------------------------------------------------------------------------
6366
# "Bind by name"
@@ -66,15 +69,17 @@
6669
rows = [
6770
{"d": "Eighth", "i": 8},
6871
{"d": "Ninth", "i": 9},
69-
{"d": "Tenth", "i": 10}
72+
{"d": "Tenth", "i": 10},
73+
{"i": 11} # Insert a NULL value
7074
]
7175

72-
cursor = connection.cursor()
76+
with connection.cursor() as cursor:
7377

74-
# Predefine maximum string size to avoid data scans and memory reallocations
75-
cursor.setinputsizes(d=20)
78+
# Predefine maximum string size to avoid data scans and memory
79+
# reallocations
80+
cursor.setinputsizes(d=20)
7681

77-
cursor.executemany("insert into mytab(id, data) values (:i, :d)", rows)
82+
cursor.executemany("insert into mytab(id, data) values (:i, :d)", rows)
7883

7984
#------------------------------------------------------------------------------
8085
# Inserting a single bind still needs tuples
@@ -85,15 +90,16 @@
8590
("Twelth",)
8691
]
8792

88-
cursor = connection.cursor()
89-
cursor.executemany("insert into mytab(id, data) values (11, :1)", rows)
93+
with connection.cursor() as cursor:
94+
cursor.executemany("insert into mytab(id, data) values (12, :1)", rows)
95+
96+
# Don't commit - this lets the demo be run multiple times
97+
# connection.commit()
9098

9199
#------------------------------------------------------------------------------
92100
# Now query the results back
93101
#------------------------------------------------------------------------------
94102

95-
# Don't commit - this lets the demo be run multiple times
96-
# connection.commit()
97-
98-
for row in cursor.execute('select * from mytab'):
99-
print(row)
103+
with connection.cursor() as cursor:
104+
for row in cursor.execute("select * from mytab order by id"):
105+
print(row)

0 commit comments

Comments
 (0)