要在Python中讀取Oracle數(shù)據(jù)庫數(shù)據(jù),需要安裝并導(dǎo)入相應(yīng)的庫。以下是一種常用的方法:
安裝cx_Oracle
庫,可以使用pip
命令進(jìn)行安裝:
pip install cx_Oracle
導(dǎo)入cx_Oracle
庫:
import cx_Oracle
建立與Oracle數(shù)據(jù)庫的連接,需要提供數(shù)據(jù)庫的連接信息:
# 連接信息
host = 'localhost'
port = 1521
service_name = 'ORCL'
user = 'username'
password = 'password'
# 建立連接
dsn = cx_Oracle.makedsn(host, port, service_name=service_name)
connection = cx_Oracle.connect(user, password, dsn)
創(chuàng)建游標(biāo)對象,用于執(zhí)行SQL查詢語句:
cursor = connection.cursor()
執(zhí)行SQL查詢語句:
sql = 'SELECT * FROM table_name'
cursor.execute(sql)
獲取查詢結(jié)果:
result = cursor.fetchall()
完整的示例代碼如下:
import cx_Oracle
# 連接信息
host = 'localhost'
port = 1521
service_name = 'ORCL'
user = 'username'
password = 'password'
# 建立連接
dsn = cx_Oracle.makedsn(host, port, service_name=service_name)
connection = cx_Oracle.connect(user, password, dsn)
# 創(chuàng)建游標(biāo)對象
cursor = connection.cursor()
# 執(zhí)行SQL查詢語句
sql = 'SELECT * FROM table_name'
cursor.execute(sql)
# 獲取查詢結(jié)果
result = cursor.fetchall()
# 打印查詢結(jié)果
for row in result:
print(row)
# 關(guān)閉連接
cursor.close()
connection.close()
請將host
、port
、service_name
、user
和password
替換為實(shí)際的數(shù)據(jù)庫連接信息,將table_name
替換為要查詢的表名。