Python 使用cx_Oracle链接Oracle数据库
准备
- Ubuntu Server 20.04 LTS
- Python3.9
- Oracle Database 11g
- Oracle Instant Client instantclient-basic-linux.x64-12.1.0.2.0
安装cx_Oracle
pip install cx_Oracle
#网络不好的情况可以使用国内源
pip install cx_Oracle -i https://pypi.tuna.tsinghua.edu.cn/simple
安装配置 Oracle Instant Client 客户端
下载对应的版本
Oracle Instant Client - Free tools and libraries for connecting to Oracle Database
解压到目录
mkdir -p /opt/oracle
cd /opt/oracle
unzip instantclient-basic-linux.x64-12.1.0.2.0.zip
设置环境变量
export ORACLE_HOME=/opt/oracle/instantclient_12_2
export PATH=$ORACLE_HOME:$PATH
export TNS_ADMIN=$ORACLE_HOME/network/admin
export LD_LIBRARY_PATH=$ORACLE_HOME:$LD_LIBRARY_PATH
export NLS_LANG='AMERICAN_AMERICA.AL32UTF8'
将客户端动态链接库添加到目录
sudo sh -c "echo /opt/oracle/instantclient_21_1 > /etc/ld.so.conf.d/oracle-instantclient.conf"
sudo ldconfig
创建tnsnames.ora文件
mkdir -p ./network/admin
vim tnsnames.ora
MyDB=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST= IP)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = )
)
)
Python 使用示例
import cx_Oracle
cx_Oracle.init_oracle_client(lib_dir=r"/opt/oracle/instantclient_12_2",
config_dir=r"/opt/oracle/instantclient_12_2/network/admin")
conn = cx_Oracle.connect('用户名/密码@主机ip地址/orcl') #用自己的实际数据库用户名、密码、主机ip地址 替换即可
curs=conn.cursor()
sql='SELECT * FROM V$VERSION' #sql语句
rr=curs.execute (sql)
row=curs.fetchone()
print(row[0])
curs.close()
conn.close()
参考链接
cx_Oracle 8 Installation — cx_Oracle 8.3.0 documentation (cx-oracle.readthedocs.io)
- 上一篇: Oracle 操作表命令
- 下一篇: 使用MinGW gcc在Windows系统编译Python扩展
不明觉历