溫馨提示×

python讀取oracle數(shù)據(jù)庫數(shù)據(jù)

小億
74
2024-01-04 04:35:23
欄目: 云計(jì)算

要在Python中讀取Oracle數(shù)據(jù)庫數(shù)據(jù),需要安裝并導(dǎo)入相應(yīng)的庫。以下是一種常用的方法:

  1. 安裝cx_Oracle庫,可以使用pip命令進(jìn)行安裝:

    pip install cx_Oracle
    
  2. 導(dǎo)入cx_Oracle庫:

    import cx_Oracle
    
  3. 建立與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)
    
  4. 創(chuàng)建游標(biāo)對象,用于執(zhí)行SQL查詢語句:

    cursor = connection.cursor()
    
  5. 執(zhí)行SQL查詢語句:

    sql = 'SELECT * FROM table_name'
    cursor.execute(sql)
    
  6. 獲取查詢結(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_nameuserpassword替換為實(shí)際的數(shù)據(jù)庫連接信息,將table_name替換為要查詢的表名。

0