记录一下使用Python连接Oracle数据库的步骤和需要注意的问题,避免以后踩坑。
1.需要下载/安装的环境配置如下:
-1.1安装Python,这里用的是Python3.8
-1.2 Oracle客户端,下载地址:https://www.oracle.com/database/technologies/instant-client/downloads.html,需要注意下版本兼容,这里下载win64下的11版
-1.3 Python连接Oracle的驱动:cx-Oracle,可以通过pip命令下载:pip install cx-Oracle==指定版本(或者不指定也可以)
2.在步骤1.2下载的Oracle客户端文件包中找到oci.dll、oraocci11.dll、oraociei11.dll这三个文件,复制到Python的site-packages文件夹中,Python38\Lib\site-packages.
3.python的编辑器中输入import cx-Oracle,没有标红报错表明环境配置成功。
4.连接数据库,传入数据库用户名、密码、主机IP端口及实例名称,有以下两种传参格式,效果一样,挑选习惯的一种即可
import cx_Oracle
con1 = cx_Oracle.connect('username/password@host:port/sid') # 用户名/密码@数据库实例
con2 = cx_Oracle.connect('username', 'password', 'host:port/sid') # 用户名,密码,数据库实例码片
5.增删改查
import cx_Oracle
# 建立连接
con = cx_Oracle.connect('sam/sam@localhost:1521/orcl') # 顺序是用户名/密码@数据库实例
# 创建游标对象
cur = con.cursor()
# 查询
sql = 'select * from tuser where username is not null'
cur.execute(sql)
# 查询结果数据集第一行数据,得到tuple类型数据
find_one = cur.fetchone()
# 查询结果数据集的到所有数据,得到list类型数据
find_all = cur.fetchall()
# 增删改,写好sql脚本,通过cur.execute()执行,然后commit()提交即可
sql1 = 'insert into tuser(id,username,useraccount) values (12,"天天","20201103001")'
sql2 = 'delete tuser where useraccount = "aalw"'
sql3 = 'update tuser set username = "bababa" where id = 5'
cur.execute(sql1)
cur.execute(sql2)
cur.execute(sql3)
con.commit() # Oracle库执行脚本一定要记住提交
con.close()