- 简介
cx_Oracle是用python连接oracle的驱动模块,参考文章:
cx_Oracle文档
木匣子
-
下载安装包
cx_Oracle-5.1.2-10g-py26-1.x86_64.rpm
oracle-instantclient12.1-basic-12.1.0.1.0-1.x86_64.rpm
oracle-instantclient12.1-devel-12.1.0.1.0-1.x86_64.rpm
官网下载地址:
http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html
http://cx-oracle.sourceforge.net/ -
安装
安装命令:
rpm -Uvh cx_Oracle-5.1.2-10g-py26-1.x86_64.rpm
rpm -Uvh oracle-instantclient12.1-basic-12.1.0.1.0-1.x86_64.rpm
rpm -Uvh oracle-instantclient12.1-devel-12.1.0.1.0-1.x86_64.rpm -
配置环境变量
vi /etc/profile在/etc/profile文件追加如下信息:
export ORACLE_HOME=/usr/lib/oracle/12.1/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 /etc/profile -
验证安装是否成功
验证方法:在目标服务器上执行: python,import cx_Oracle
如果验证失败,参考5异常处理
- 异常处理
如果出现下面的错误:
[root@client oracle]# python
import cx_Oracle
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: libclntsh.so.11.1: cannot open shared object file: No such file or directory
ImportError: libclntsh.so.11.1: cannot open shared object file: No such file or directory
这是由于驱动文件名称不对引起的
在服务器上执行命令:
find / -name libclntsh.so.*
[root@client oracle]# find / -name libclntsh.so.*
/usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1
可见是文件名称不对,执行如下命令:
cp /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1 /usr/lib/oracle/12.1/client64/lib/libclntsh.so.11.1
重新执行第四步,验证安装是否成功
- cx_Oracle增删改查
import cx_Oracle
- 连接
dsn=cx_Oracle.makedsn(host, int(port), dbname)
self.conn = cx_Oracle.connect(user, passwd ,dsn)
self.cursor = self.conn.cursor() - 插
def insert(self, sql, param, flag = True):
sql = self.sqltran(sql, param)
self.cursor.execute(sql)
self.conn.commit() - 查
def selectall(self, sql, param=None):
sql = self.sqltran(sql, param)
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result - 更新
def update(self, sql, param=None, flag = True):
sql = self.sqltran(sql, param)
self.cursor.execute(sql)
self.conn.commit() - 删
def delete(self, sql, param=None):
sql = self.sqltran(sql, param)
self.cursor.execute(sql)
self.conn.commit() - 关闭连接
def del( self ):
if self.conn :
self.conn.close() - sql转换
def sqltran(self,sql,param):
for i in range(0,len(param)):
sql = sql.replace('%s',str(param[i]),1)
return sql - 测试方法
if name == 'main':
param = ('id','name','addr',1)
sql1= 'select id ,name, addr from test'
sql0= 'select %s,%s,%s from test'
sql2= 'insert into test (%s,%s,%s)values(4,4,4)'
sql3= 'update test set name=222 where id=%s'
sql4= 'delete from test where id=%s'
print oracle.selectall(sql0,param)
print oracle.insert(sql2, param)
print oracle.selectOne(sql0,param)
print oracle.update(sql3,('3'))
print oracle.delete(sql4,('4'))
print oracle.selectall(sql0,param)
print 'success'
网友评论