使用python连接Oracle数据并读取数据库表
1、cx_Oracle
pip install cx_Oracle
2、Oracle客户端
下载Oracle客户端,下载页面。
文件下载后,解压
import os
import traceback
import cx_Oracle as Ora
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' # 防止乱码问题
os.environ['Path'] = r'E:\instantclient_21_3' #oracle客户端安装位置
def read_oracle(query):
user_name = "user"
passwd = "password"
ip_port = "192.168.0.1:3468"
db = "dbname"
result = []
conn = Ora.connect(user_name, passwd, '{}/{}'.format(ip_port, db), encoding='UTF-8')
try:
cur = conn.cursor()
re_fetch = cur.execute(query)
result = re_fetch.fetchall()
conn.close()
except Exception as err:
print("Error:\t{}".format(err))
print(traceback.format_exc())
conn.close()
return result
if __name__ == '__main__':
query_sql = "select * from table"
res = read_oracle(query_sql)
print(res)