python -- 链接 orclae cx_Oracle的使用 二

转:https://www.cnblogs.com/cyxiaer/p/9396861.htmlhtml

 

必需的Oracle连接库的下载地址:https://www.oracle.com/technetwork/topics/winx64soft-089540.htmlpython

只链接数据库的话没必要安装客户端:sql

1. 把cx_Oracle的客户端文件复制到site-packages/ 目录下,多是Python, Anaconda, venv下面的安装包里数据库

2. 把下载的instantclient文件夹下的.dll文件所有复制到site-packages/ 目录下windows

3. 把instantclient文件解压后的地址添加到环境变量里面去。网络

4. 建立数据库链接.oracle

建立数据库链接connect和关闭数据库链接close

建立数据库链接的三种方式:python2.7

方法一:用户名、密码和监听分开写函数

import cx_Oraclefetch

db=cx_Oracle.connect('username/password@host/orcl')

db.close()

 

方法二:用户名、密码和监听写在一块儿

import cx_Oracle

db=cx_Oracle.connect('username','password','host/orcl')

db.close()

 

方法三:配置监听并链接

import cx_Oracle

tns=cx_Oracle.makedsn('host',1521,'orcl')

db=cx_Oracle.connect('username','password',tns)

db.close()

 

cx_Oracle错误:Unable to acquire Oracle environment handle

错误表现:
cx_Oracle链接Oracle数据库的时候报错:
cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle

解决办法:将instantclient目录下的全部*.dll文件拷贝到Python27\Lib\site-packages目录下,问题解决

SQLAlchemy Oracle 的中文问题

你须要设置 NLS_LANG 环境变量,不然你读取出来的中文多是乱码,或者当 insert 的数据有中文时会致使 Unicode 编码错误。

你能够在 Python 代码中这么设置环境变量

# 设置编码,不然: # 1. Oracle 查询出来的中文是乱码 # 2. 插入数据时有中文,会致使 # UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-7: ordinal not in range(128) os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

No module named cx_Oracle:
import cx_Oracle ImportError: No module named cx_Oracle

若是安装的 python 64 位,须要把cx_Oracle文件复制到 /usr/lib64/python2.7/site-packages/ 目录下

cd /usr/lib/python2.7/site-packages/ cp cx_Oracle.so /usr/lib64/python2.7/site-packages/cx_Oracle.so cp cx_Oracle-5.1.2-py2.7.egg-info /usr/lib64/python2.7/site-packages/cx_Oracle-5.1.2-py2.7.egg-info

UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position ... 问题解决办法

目标文件的编码是致使标题所指问题的罪魁祸首
f = open("out.html","w")

,在windows下面,新文件的默认编码是gbk,这样的话,python解释器会用gbk编码去解析咱们的网络数据流txt,然而txt此时已是decode过的unicode编码,这样的话就会致使解析不了,出现上述问题。 解决的办法就是,改变目标文件的编码:

f = open("out.html","w",encoding='utf-8')
问题解决。

1. cx_Oracle
cx_Oracle模块是Python链接Oracle数据库的模块,在Python中,若是要链接Oracle,必须先安装cx_Oracle模块。 
cx_Oracle的下载地址:https://pypi.python.org/pypi/cx_Oracle/ 
选择和操做系统、Python版本一致的安装包进行安装。固然为了省事儿,你也能够直接使用pip命令来安装cx_Oracle。

pip install cx_Oracle

安装完成后,在交互模式下输入import cx_Oracle,不报错,说明安装成功。

2. 链接Oracle数据库
方法一:用户名、密码、监听分开写

import cx_Oracle
db=cx_Oracle.connect('username','password','host:port/sid')


方法二:用户名、密码、监听写一块儿

import cx_Oracle 
db=cx_Oracle.connect('username/password@host:port/sid') 

方法三:先配置监听,后链接

import cx_Oracle 
tnsname = cx_Oracle.makedsn('host', port,'sid') 
db = cx_Oracle.connect('username','password',tnsname) 

说明:代码中username、password、host、port、sid换成实际数据库的用户名、密码、主机名或主机IP、数据库实例名。

3. 建立游标
cx_Oracle中,对于数据库的增删改查操做须要经过游标来进行,游标的建立语句以下:

cur=db.cursor()

4. 执行sql语句
Sql语句书写:不须要从外部传入参数,能够直接书写sql语句,而后使用execute执行sql便可;若是须要从外部传入参数,在须要传入参数的地方使用变量,并在变量前加“:”,而后经过prepare加载sql语句。

cur.prepare:若是执行的sql语句须要传外部参数,能够先用这个函数加载sql语句,而后再经过execute或executemany加参数执行。
cur.execute:执行单条sql语句。
cur.executemany:执行多条sql语句。
关于execute须要说明的是若是执行的sql语句不须要从外部传入参数,那么能够跳过prepare,直接将sql语句做为execute的第一个参数来执行sql。

db.commit():执行提交操做,增、删、改后须要使用。
cur.fetchall:在查询以后使用,获取全部查询到的结果记录。
cur.fetchone:在查询以后使用,获取一条查询到的结果记录。
关于fetchall和fetchone须要说明的是查询到的记录一旦被提取,就不能再次被提取,无论是用fetchall提取仍是使用fetchone提取。

res = cur.fetchall()[0][0].read();

fetchall和fetchone返回的是元组,加上[][],能够直接取到值。

for result in cur:  #循环从游标获取每一行并输出该行。
    print result
写完游标能够去循环游标让它输出结果。
 

查询: 
须要外部参数:

>>> cur.prepare('select * from t_emp a where a.empid=:id')
>>> cur.execute(None,{'id':id})
<cx_Oracle.Cursor on <cx_Oracle.Connection to cs@192.168.1.226:1521/db_emp>>
>>> cur.fetchall()

不须要外部参数:

>>> cur.execute("select e.empid,e.empname from t_emp e")
<cx_Oracle.Cursor on <cx_Oracle.Connection to cs@192.168.102.219:1521/t45>>
>>> cur.fetchone()
(1, '张三')
>>> cur.fetchall()
[(2, '李四'), (3, '王五'), (4, '沈六'), (5, '田七'), (6, '凤九')]

增长、删除、修改:

单条增长:

>>> sql="insert into t_emp(empid,empname) values (:empid,:empname)"
>>> cur.prepare(sql)
>>> cur.execute(None,{'empname':'李绅','empid':7})
>>> db.commit()

多条增长:

>>> sql="insert into t_emp(empid,empname) values (:empid,:empname)"
>>> cur.prepare(sql)
>>> cur.executemany(None,[{'empname':'赵青','empid':8},{'empname':'萧远','empid':9}])
>>> db.commit()

单条修改:

>>> sql="update t_emp a set a.empname='清月' where a.empid=:empid"
>>> cur.prepare(sql)
>>> cur.execute(None,{empid:"4"})
>>> db.commit()

多条修改:

>>> sql="update t_emp a set a.empname=:empnamewhere a.empid=:empid"
>>> cur.prepare(sql)
>>> cur.executemany(None,[{'empid':"5","empname":"明月"},{'empid':"6","empname":"乐天"}])
>>> db.commit()

删除:

>>> cur.execute('delete from t_emp a where a.empid in (3,4,5,6)')
>>> db.commit()

5. 关闭游标
sql语句执行结束,再也不使用时,应关闭游标,关闭游标的语句为:

cur.close()

6. 关闭数据库
数据库操做结束后应及时释放链接,关闭数据库链接的语句为:

db.close()

7. 我写的一个Oracle数据库操做类
cx_Oracle是Python的Oracle操做的模块,在使用时导入就能使用,可是由于数据库使用时涉及链接、操做、提交、关闭链接等一系列操做,不可能每次使用时都把这些操做用代码写一遍,因此我把这些操做放到一个类里,在实际使用时来调用这个类就好了。

复制代码
#coding=utf-8
import cx_Oracle
class OpOracle():
    def __init__(self,ora_username,ora_password,ora_host,ora_port,ora_sid):
        '''初始化Oracle链接'''
        self.db=cx_Oracle.connect(ora_username,ora_password,ora_host+':'+ora_port+'/'+ora_sid)
        self.cur=self.db.cursor()
    def Ora_Select(self,strSql):
        '''执行strSql语句进行查询'''
        self.cur.execute(strSql)
        return self.cur.fetchall()
    def Ora_IUD_Single(self,strSql):
        '''执行strSql语句进行增长、删除、修改操做'''
        self.cur.execute(strSql)
        self.db.commit()
    def Ora_IUD_Multi(self,strSql,List):
        '''执行strSql语句进行增长、删除、修改操做,对应参数使用List中的数据'''
        self.cur.prepare(strSql)
        self.cur.executemany(None,List)
        self.db.commit()
    def Ora_Cur_Close(self):
        '''关闭游标'''
        self.cur.close()
    def Ora_db_Close(self):
        '''关闭Oracle数据库链接'''
        self.db.close()
复制代码

 

我把这段代码保存在OpOracle.py文件中,使用时直接导入这个文件便可。如:

from OpOracle import OpOracle
ora=OpOracle('cs','ceshi','192.168.1.226','1521','db_emp')
l_emp=ora.Ora_Select('select * from t_emp')    #查询t_emp表的数据并保存到l_emp列表中
ora.Ora_IUD_Single('delete from t_emp a where a.empid=1')  #删除empid为1的记录
ora.Ora_Cur_Close()
ora.Ora_db_Close()     #最后记得关闭游标和数据库链接
相关文章
相关标签/搜索