一、背景
项目需要,通过python连接后数据库后,获取想要的数据,然后处理;但是由于是第一次链接Oracle,踩了一些小坑,记录下;
二、基本链接配置
import cx_Oracle
tns = cx_Oracle.makedsn("127.0.0.1","1521","orcl") #监听Oracle数据库
db = cx_Oracle.connect("username","password",tns) #连接数据库
db.close() #关闭数据库
监听Oracle数据库的makedsn(host,port,dbname)方法的参数使用说明:
①host参数,为数据库服务器的IP地址。如:host=“127.0.0.1”,“127.0.0.1”指向本地计算机的IP地址。设置为host=“localhost"时,则代表指向本地计算机。
②port参数,为Oracle数据库安装时的端口号,如port=1521
③dbname参数,为数据库名(又叫数据库实例),如dbname=“orcl”
监听方法主要预先判断Oracle数据库系统是否正常启动。
连接数据库通过connect()方法进行。
①username:为访问数据库所需要的用户名
②password:为访问数据库所需要的密码
这两个参数在Oracle数据库安装或通过数据库管理工具设置
————————————————
原文链接:https://blog.csdn.net/m0_55697123/article/details/119858674
三、问题一:cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "D:\tool\instantclient_11_2\oci.dll is not the correct architecture"
本地已经配置了链接的基本客户端设置,且环境变量配置的是installclient_11_2
说明:上面的installclient_11_2是第一次配置
installclient_21_3是由于链接Navicat时,由于版本过低,安装的新包
pycharm执行后,报错:
修改环境变量没有成功;
最后通过查看官网设置一下初始化环境即可:
官网路径:https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html
自己代码配置如下:
import cx_Oracle
# 1、监听Oracle数据库
cx_Oracle.init_oracle_client(lib_dir=r"D:\tool\instantclient_21_3")
tns = cx_Oracle.makedsn("172.16.xx.xx", "1521", "ORCL")
# 2、连接数据库
db = cx_Oracle.connect("xxx", "xxx", tns)
# 获取操作游标
cursor = db.cursor()
cursor.execute("SELECT * FROM XXX")
one = cursor.fetchone()
print(one)
设置后,执行成功!