用Python连接Oracle数据库容易吗?

ello,大家好!本次介绍的内容是如何使用Python连接Oracle数据库!看起来很简单,但实际上就是这么简单。学习本节内容后,相信老铁们能用Python撸起你们那庞大的Oracle数据库了。Well,下面开始进入主题!


分析步骤如下


1. 了解源端和目标端的用户信息

2. Oracle数据库配置信息

3. Python主机配置

4. Python测试连接Oracle数据库



了解源端和目标端的用户信息

扫描二维码关注公众号,回复: 12734312 查看本文章

-- Python主机的信息
(pyOracle) [python@PYMY-DDB pyOracle]$ id python
uid=501(python) gid=501(python) groups=501(python)

-- 目标数据库的用户信息
[[email protected]]/home/grid$id grid
uid=302(grid) gid=301(oinstall) groups=301(oinstall),302(dba),304(asmadmin),305(asmdba),306(asmoper)

[[email protected]]/home/oracle$id oracle
uid=301(oracle) gid=301(oinstall) 01(oinstall),302(dba),303(oper),304(asmadmin),305(asmdba)


Oracle数据库配置信息


1.  查看数据库服务器的IP地址

[[email protected]]/home/grid$ifconfig -a
eth0      Link encap:Ethernet  HWaddr 00:0C:29:CF:B6:31  
          inet addr:192.168.117.100  Bcast:192.168.117.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fecf:b631/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1463 errors:0 dropped:0 overruns:0 frame:0
          TX packets:913 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:132368 (129.2 KiB)  TX bytes:142387 (139.0 KiB)

eth1      Link encap:Ethernet  HWaddr 00:0C:29:CF:B6:3B  
          inet addr:10.10.10.100  Bcast:10.255.255.255  Mask:255.0.0.0
          inet6 addr: fe80::20c:29ff:fecf:b63b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:51 errors:0 dropped:0 overruns:0 frame:0
          TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:7370 (7.1 KiB)  TX bytes:816 (816.0 b)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:7540 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7540 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:486091 (474.6 KiB)  TX bytes:486091 (474.6 KiB)


2.  查看监听服务

[[email protected]]/home/grid$lsnrctl status

LSNRCTL for Linux: Version 11.2.0.4.0 - Production on 21-FEB-2019 17:48:50

Copyright (c) 19912013, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=LISTENER)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for Linux: Version 11.2.0.4.0 - Production
Start Date                21-FEB-2019 15:38:33
Uptime                    0 days 2 hr. 10 min. 16 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Listener Parameter File   /oracle/app/grid_home/11.2.0/grid/network/admin/listener.ora
Listener Log File         /oracle/app/grid_home/11.2.0/grid/log/diag/tnslsnr/RACZJ-DDB/listener/alert/log.xml
Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=LISTENER)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.117.100)(PORT=1521)))
Services Summary...
Service "+ASM" has 1 instance(s).
  Instance "+ASM", status READY, has 1 handler(s) for this service...
Service "ORCL" has 1 instance(s).
  Instance "ORCL", status READY, has 1 handler(s) for this service...
Service "ORCLXDB" has 1 instance(s).
  Instance "ORCL", status READY, has 1 handler(s) for this service...
The command completed successfully


3.  查看Oracle数据库名

SQL> show parameter name

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
cell_offloadgroup_name               string
db_file_name_convert                 string
db_name                              string      ORCL
db_unique_name                       string      ORCL
global_names                         boolean     FALSE
instance_name                        string      ORCL
lock_name_space                      string
log_file_name_convert                string
processor_group_name                 string
service_names                        string      ORCL



Python主机配置


1.  安装Oracle 客户端

[root@PYMY-DDB rpm]# ls -l
total 60272
-rwxrw-rw-  1 root root 59865008 Jan 16 17:44 oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm
-rwxrw-rw-  1 root root   610222 Jan 16 17:50 oracle-instantclient11.2-devel-11.2.0.4.0-1.x86_64.rpm

[root@PYMY-DDB rpm]# rpm -ivh oracle-instantclient11.2-basic-11.2.0.4.0-1.x86_64.rpm 
Preparing...                ########################################### [100%]
   1:oracle-instantclient11.########################################### [100%]
[root@PYMY-DDB rpm]# rpm -ivh oracle-instantclient11.2-devel-11.2.0.4.0-1.x86_64.rpm 
Preparing...                ########################################### [100%]
   1:oracle-instantclient11.########################################### [100%]


2.  Python用户环境变量

[python@PYMY-DDB ~]$ cat .bash_profile 
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export PATH
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
export ORACLE_HOME=/usr/lib/oracle/11.2/client64
export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib


[python@PYMY-DDB ~]$ source .bash_profile 


3.  创建虚拟环境

[python@PYMY-DDB ~]$ pyenv virtualenv 3.6.5 pyOracle
Requirement already satisfied: setuptools in /home/python/.pyenv/versions/3.6.5/envs/pyOracle/lib/python3.6/site-packages
Requirement already satisfied: pip in /home/python/.pyenv/versions/3.6.5/envs/pyOracle/lib/python3.6/site-packages


4.  查看和加载虚拟环境版本

[python@PYMY-DDB ~]$ pyenv virtualenvs
  2.7.15/envs/autoDjango (created from /home/python/.pyenv/versions/2.7.15)
  2.7.15/envs/testDjango (created from /home/python/.pyenv/versions/2.7.15)
  3.6.5/envs/pyOracle (created from /home/python/.pyenv/versions/3.6.5)
  autoDjango (created from /home/python/.pyenv/versions/2.7.15)
  pyOracle (created from /home/python/.pyenv/versions/3.6.5)
  testDjango (created from /home/python/.pyenv/versions/2.7.15)

[python@PYMY-DDB ~]$ pyenv activate pyOracle
pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior.


5.  升级pyOracle项目的pip

yOracle) [python@PYMY-DDB ~]$ pip install --upgrade pip
Collecting pip
  Using cached https://files.pythonhosted.org/packages/d7/41/34dd96bd33958e52cb4da2f1bf0818e396514fd4f4725a79199564cd0c20/pip-19.0.2-py2.py3-none-any.whl
Installing collected packages: pip
  Found existing installation: pip 9.0.3
    Uninstalling pip-9.0.3:
      Successfully uninstalled pip-9.0.3
Successfully installed pip-19.0.2


6.  安装和检查cx_Oracle模块

(pyOracle) [python@PYMY-DDB ~]$ pip install cx_Oracle

(pyOracle) [python@PYMY-DDB ~]$ python -c "import cx_Oracle"



Python测试连接Oracle数据库

1.  测试连接Oracle数据库
(pyOracle) [python@PYMY-DDB pyOracle]$ cat connoracle.py 

#!/usr/bin/python
#coding=utf8

#导入cx_Oracle模块
import cx_Oracle

#创建到Oracle数据库的连接并赋给变量
db=cx_Oracle.connect('scott/[email protected]:1521/ORCL')

#创建游标并赋给变量cursor
execsql=db.cursor()

#执行Oracle SQL语句
execsql.execute('select sysdate from dual')

#获取执行结果并赋给变量data
#这里fetchone表示获取一行,fetchall为获取所有行
#fetchone返回的是一个字符串
#fetchall返回的是一个列表,哪怕结果只有一行
result=execsql.fetchone()


#打印结果
print ('Database time: %s ' %result)

#关闭数据库连接
execsql.close()
db.close()


2.  Python成功连接Oracle数据库

(pyOracle) [python@PYMY-DDB pyOracle]$ python connoracle.py     
Database time: 2019-02-21 15:47:41 


3.   测试查询Oracle的数据文件信息

(pyOracle) [python@PYMY-DDB pyOracle]$ cat connoracle_dbf.py 

#!/usr/bin/python
# coding=utf8
import cx_Oracle

def oraclesql(execsql):
    # 这里我们使用python的open方法打开文件并读取文件内容作为SQL语句执行
    # 可使用绝对路径或相对路径
    sqlfile = open('/oracle/scripts/datafile.sql''r')
    # fp=open('./tablespace.sql','r')
    sqlfilecontent = sqlfile.read()
    execsql.execute(sqlfilecontent)
    result = execsql.fetchall()
    return result

if __name__ == "__main__":
    ipaddress = '192.168.117.100'
    username = 'sys'
    password = 'oracle'
    port = '1521'
    tnsname = 'ORCL'
    # 这里我们利用Python的异常处理来捕获异常,具体用法请参考文章开始提到的教程
    try:
        # 这里我们使用sysdba权限连接oracle数据库(和上期连接普通用户的不同)
        db = cx_Oracle.connect(username + '/' + password + '@' + ipaddress + ':' + port + '/' + tnsname,mode=cx_Oracle.SYSDBA)
    except Exception as e:
        content = (tnsname + ' is Unreachable,The reason is ' + str(e)).strip()
        print(content)
    else:
        execsql = db.cursor()
        result = oraclesql(execsql)
        execsql.close()
        db.close()
        # 由于上面获取的是一个列表(多行),这里使用for循环来遍历
        # 注意i也是一个列表

        print ('数据文件编号  表空间名称   数据文件名字')
        for i in result:
            print (i)


4.  查看Oracle查询数据文件的SQL语句

(pyOracle) [python@PYMY-DDB pyOracle]$ cat /oracle/scripts/datafile.sql

select file_id, tablespace_name,file_name from dba_data_files order by 1


5.  Python成功查询Oracle的数据文件信息

(pyOracle) [python@PYMY-DDB pyOracle]$ python connoracle_dbf.py             
数据文件编号  表空间名称   数据文件名字
(1'SYSTEM''+DATA/orcl/datafile/system.266.978200739')
(2'SYSAUX''+DATA/orcl/datafile/sysaux.260.978200741')
(3'UNDOTBS1''+DATA/orcl/datafile/undotbs1.264.978200743')
(4'USERS''+DATA/orcl/datafile/users.263.978200743')
(5'EXAMPLE''+DATA/orcl/datafile/example.258.978200911')
(6'USER_STU_DATA''+DATA/orcl/datafile/user_stu_data.256.979408775')
(7'OGG''+DATA/orcl/datafile/ogg.268.979421969')
(8'SQLTUNE_DATA''+DATA/orcl/datafile/sqltune_data.269.986846807')
(9'SQLTUNE_DATA''+DATA/orcl/datafile/sqltune_data.270.986847073')
(10'SQLTUNE_DATA''+DATA/orcl/datafile/sqltune_data.271.986847785')
(11'SQLTUNE_DATA''+DATA/orcl/datafile/sqltune_data.272.986847789')
(12'SQLTUNE_DATA''+DATA/orcl/datafile/sqltune_data.273.986847891')


总结

老铁们,Python连接Oracle数据库是不是很简单呢?如果有疑惑的话,可以后台咨询我喔!最后,非常感谢您的阅读!


猜你喜欢

转载自blog.51cto.com/15061934/2653788