简介
cx_Oracle是用python连接oracle的驱动模块.
下载安装包
- cx_Oracle-5.1-10g-py27-1.x86_64.rpm下载
- oracle-instantclient-basic-10.2.0.3-1.x86_64.rpm下载
- oracle-instantclient-devel-10.2.0.3-1.x86_64.rpm下载
安装
- 因为我机器安装了两个版本的python,所以安装cx_Oracle的时候指定的安装目录,如只有一个版本,可不指定:
rpm -ivh –prefix=/usr/local/python2.7.13/ cx_Oracle-5.1-10g-py27-1.x86_64.rpm - rpm -ivh oracle-instantclient-basic-10.2.0.3-1.x86_64.rpm
- rpm -ivh oracle-instantclient-devel-10.2.0.3-1.x86_64.rpm
配置环境变量
修改当前用户~/.bash_profile文件,末尾添加如下信息:
export ORACLE_HOME=/usr/lib/oracle/10.2.0.3/client64
export PATH=$PATH:$ORACLE_HOME/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib
export TNS_ADMIN=$ORACLE_HOME/network/admin
然后执行source ~/.bash_profile
验证
输入python后,进入python编辑命令行,输入如下代码:
import cx_Oracle
若无异常则说明安装成功
附录
连接和关闭
db=cx_Oracle.connect('user','pwd','address:port/service_name')
print db.version
db.close()
db=cx_Oracle.connect('user/pwd@address:port/service_name')
print db.version
db.close()
tns=cx_Oracle.makedsn('tnsname',port,'service_name')
db=cx_Oracle.connect('user','pwd',tns)
print tns
print db.version
db.close()
执行SQL
tns=cx_Oracle.makedsn('tnsname',port,'service_name')
db=cx_Oracle.connect('user','pwd',tns) --创建连接
cr=db.cursor() --创建cursor
sql='select * from phone'
cr.execute(sql) --执行sql 语句
print "\nThis is Fetchall!"
rs=cr.fetchall() --一次返回所有结果集
print "print all:(%s)" %rs
print "\n print by row:"
for x in rs:
print x
print "\nThis is Fetone!"
cr.execute(sql)
while(1):
rs=cr.fetchone() --一次返回一行
if rs ==None:break
print rs
--使用参数查询
print "\n select with parameter:"
pr={'id':3,'tel':13888888888}
cr.execute('select * from phone where id=:id or phone=:tel',pr)
--这里我们将参数作为一个字典来处理的
rs=cr.fetchall()
print rs
cr.execute('select * from phone where id=:myid or phone=:myphone',myid=2,myphone=13888888888)
--这里我们直接写参数
rs=cr.fetchall()
print rs
cr.close()
db.close()