|
| 1 | +#------------------------------------------------------------------------------ |
| 2 | +# Example.py |
| 3 | +# |
| 4 | +# Demonstrate how to perform a database insert and query with Python |
| 5 | +# in Oracle Database Cloud services such as Exadata Express, |
| 6 | +# Autonomous Transaction Processing, Autonomous Data Warehouse, and |
| 7 | +# others. |
| 8 | +# |
| 9 | +# Before running this script: |
| 10 | +# - Install Oracle Instant Client |
| 11 | +# - Download and install the cloud service wallet |
| 12 | +# - Modify the connect() call below to use the credentials for your database. |
| 13 | +# See your cloud service's documentation for details. |
| 14 | +# |
| 15 | +#------------------------------------------------------------------------------ |
| 16 | + |
| 17 | +from __future__ import print_function |
| 18 | + |
| 19 | +import cx_Oracle |
| 20 | + |
| 21 | +con = cx_Oracle.connect('username', 'password', 'connect_string') |
| 22 | +cur = con.cursor() |
| 23 | + |
| 24 | +# Create a table |
| 25 | + |
| 26 | +cur.execute(""" |
| 27 | +begin |
| 28 | + execute immediate 'drop table mycloudtab'; |
| 29 | + exception |
| 30 | + when others then |
| 31 | + if sqlcode not in (-00942) then |
| 32 | + raise; |
| 33 | + end if; |
| 34 | +end; |
| 35 | +"""); |
| 36 | + |
| 37 | +cur.execute('create table mycloudtab (id number, data varchar2(20))') |
| 38 | + |
| 39 | +# Insert some data |
| 40 | + |
| 41 | +rows = [ (1, "First" ), (2, "Second" ), |
| 42 | + (3, "Third" ), (4, "Fourth" ), |
| 43 | + (5, "Fifth" ), (6, "Sixth" ), |
| 44 | + (7, "Seventh" ) ] |
| 45 | + |
| 46 | +cur.executemany("insert into mycloudtab(id, data) values (:1, :2)", rows) |
| 47 | + |
| 48 | +# Query the data |
| 49 | + |
| 50 | +cur.execute('select * from mycloudtab') |
| 51 | +res = cur.fetchall() |
| 52 | +print(res) |
0 commit comments