Python 连接 Oracle数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 连接 Oracle数据库相关的知识,希望对你有一定的参考价值。
1.环境设置
[[email protected] ~]# cat /etc/redhat-release
CentOS release 6.9 (Final)
[[email protected] ~]# python -V
Python 2.6.6
版本:Oracle 12c
2.前提:安装cx_Oracle模块依赖包
由于使用Python连接Oracle,所以需要下载oracle客户端包
官网:http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html?ssSourceSiteId=otncn
oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm
oracle-instantclient12.1-devel-12.1.0.2.0-1.x86_64.rpm
oracle-instantclient12.1-sqlplus-12.1.0.2.0-1.x86_64.rpm
[[email protected] ~]# rpm - ivh oracle-instantclient12.1-*
3.设置环境变量
[[email protected] ~]# cat ~/.bash_profile
export /usr/lib/oracle/12.1/client64/ export LD_LIBRARY_PATH=/usr/lib/oracle/12.1/client64/lib
4.安装cx_Oracle模块
官网:https://pypi.python.org/pypi/cx_Oracle
cx_Oracle-6.2.1.tar.gz
[[email protected] ~]# tar -zxvf cx_Oracle-6.2.1.tar.gz [[email protected] cx_Oracle-6.2.1]# python setup.py install
可能会遇到报错
error: command 'gcc' failed with exit status 1
解决方法:
yum install python-devel
yum install libevent-devel
5.查看是否可以导入cx_Oracle模块
[[email protected] ~]# python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_Oracle
>>> #无报错说明成功
6.编写Python连接oracle数据库脚本(oracle用户,因为我这里都是用oracle用户权限安装的)
[[email protected] ~]$ cat py_oracle.py
#!/usr/bin/env python #-*- coding: UTF-8 -*- import cx_Oracle #导入模块 db=cx_Oracle.connect('system/[email protected]:1521/ORCL') #连接user/[email protected]:端口/instance cursor = db.cursor() #创建游标对象 cursor.execute('select sysdate from dual') #执行命令 data = cursor.fetchone() #返回值 print('Database time:%s' % data) 打印输出 cursor.close() #关闭游标对象 db.close() #关闭数据库
7.执行脚本
[[email protected] ~]$ python py_oracle.py
Database time:2018-03-20 20:47:59
以上是关于Python 连接 Oracle数据库的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Toad for Oracle 中使用自定义代码片段?