一、Oracle库
1、环境配置(以我的机器为例)
1.1、python版本![](https://i-blog.csdnimg.cn/blog_migrate/97fb65bececdf646a801893d430f6b9b.png)
1.2、oracle
1.3、cx_Oracle驱动配置
python链接oracle的驱动包,这个需要自己安装,cx_Oracle发行版本历史在这个网址中下载对应的驱动,下载驱动的时候一定要选好对应的版本
上面的工作做好之后,在刚才下载好的oracle客户端版本中找到下面三个文件:oci.dll、oraocci11.dll、oraociei11.dll,将这几个dll文件复制到:Python\Python36-32\Lib\site-packages文件夹中。
1.4、检验是否成功
输入 import cx_Oracle如果未报错则成功安装驱动。
2、数据库操作
2.1、数据库连接
conn = cx_Oracle.connect('xzt/xzt@localhost/testdb')#这里的顺序是用户名/密码@oracleserver的ip地址/数据库名字
cur = conn.cursor()
sql = "SELECT * FROM DUAL"
cur.execute(sql)
cur.close()
conn.commit()
conn.close()
2.2、数据查询
import cx_Oracle
# 连接数据库
conn = cx_Oracle.connect('python/python@localhost/orcl')
cursor = conn.cursor()
cursor.execute("SELECT * FROM student")
rows = cursor.fetchall() # 得到所有数据集
for row in rows:
print("%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]))
print("Number of rows returned: %d" % cursor.rowcount)
cursor.execute("SELECT * FROM student")
while (True):
row = cursor.fetchone() # 逐行得到数据集
if row == None:
break
print("%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]))
print("Number of rows returned: %d" % cursor.rowcount)
cursor.close()
conn.close()
2.2、执行sql语句
import cx_Oracle
conn = cx_Oracle.connect('python/python@localhost/orcl')
cursor = conn.cursor()
sql = 'CREATE TABLE TEST1(ID INT primary key , C1 VARCHAR2(50), C2 VARCHAR2(50))'
cursor.execute(sql)
conn.commit() # 记得提交
cursor.close() # 关闭游标
conn.close() # 关闭连接