--Using Oracle Cloud
It is not limited to cx_Oracle, but to connect to Oracle Database, you need the user name of the DB to be connected, the password of that user, and the connection destination information (either TNS connector or EZCONNECT). These need to be prepared in advance. In cx_Oracle, you can connect to the DB by specifying these in the argument of the method called connect (). There is also an alias called connection (), which you can use.
For example, if the user name is "scott", the password is "Tiger", and the connection destination information is "db1"
connection = cx_Oracle.connect("scott", "Tiger", "db1")
Connect to the DB by specifying the user name in the first argument (argument name user), the password (argument name password) in the second argument, and the connection destination information in the third argument (argument name dsn). I can do it. Even if the connection destination information is in EZCONNECT format such as "hostname1: 1521 / db1.oracle.com"
connection = cx_Oracle.connect("scott", "Tiger", "hostname1:1521/db1.oracle.com")
And just specify it in the same way. The dsn argument is not required for local connections using the environment variable ORACLE_SID.
This method returns a Connection object. After that, perform operations such as issuing SQL to the acquired Connection object (variable connection in the above example).
Call the close () method of the Connection object.
connection.close()
The following is a sample application that connects to a DB, displays the version information of the connection destination DB (second line from the bottom), and disconnects.
sample02a.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cx_Oracle
USERID = "admin"
PASSWORD = "FooBar"
DESTINATION = "atp1_low"
connection = cx_Oracle.connect(USERID, PASSWORD, DESTINATION)
print(connection.version)
connection.close()
Closing open resources is a programming rule. However, in reality, it's easy to forget about closing. Python provides a with syntax to ensure that open resources are closed. And cx_Oracle supports the with syntax. By coding as follows, it is possible to securely close the connection.
sample02b.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cx_Oracle
USERID = "admin"
PASSWORD = "FooBar"
DESTINATION = "atp1_low"
with cx_Oracle.connect(USERID, PASSWORD, DESTINATION) as connection:
print(connection.version)
Recommended Posts