-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest_oracle.py
93 lines (74 loc) · 2.14 KB
/
test_oracle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python3
"""
Simple script to test Oracle python driver
@see
https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html#quick-start-cx-oracle-installation
https://blogs.oracle.com/oraclemagazine/perform-basic-crud-operations-using-cx-oracle-part-1
"""
from config import settings
import cx_Oracle
from pprint import pprint
def get_connection():
dsn = "{}/{}".format(settings.DB_HOST, settings.DB_SID)
connection = cx_Oracle.connect(settings.DB_USER, settings.DB_PASS, dsn)
return connection
def create_table(conn):
cursor = conn.cursor()
sql = """
CREATE TABLE student (
id integer NOT NULL
, first_name VARCHAR(32) NOT NULL
, last_name VARCHAR(32) NOT NULL
, PRIMARY KEY (id)
)
"""
try:
result = cursor.execute(sql)
pprint("create result: {}".format(result))
except Exception as exc:
print("create_table - got exception: {}".format(exc))
finally:
cursor.close()
def insert_table(conn):
cursor = conn.cursor()
sql = """
INSERT INTO student (id, first_name, last_name)
WITH names AS (
SELECT 1, 'Ruth', 'Fox' FROM dual UNION ALL
SELECT 2, 'Isabelle', 'Squirrel' FROM dual UNION ALL
SELECT 3, 'Justin', 'Frog' FROM dual UNION ALL
SELECT 4, 'Lisa', 'Owl' FROM dual
)
SELECT * FROM names
"""
try:
cursor.execute(sql)
conn.commit()
except Exception as exc:
print("insert_table - got exception: {}".format(exc))
finally:
cursor.close()
def read_table(conn):
cursor = conn.cursor()
sql = """
SELECT
id, first_name, last_name
FROM
student
WHERE
id >= :id
"""
try:
cursor.execute(sql, id=2)
print("read_table:")
for id, fname, lname in cursor:
print("\nrow: ", id, fname, lname)
finally:
cursor.close()
def main():
conn = get_connection()
create_table(conn)
insert_table(conn)
read_table(conn)
if __name__ == '__main__':
main()