用Python鏈接Oracle數據庫容易嗎?

ello,你們好!本次介紹的內容是如何使用Python鏈接Oracle數據庫!看起來很簡單,但實際上就是這麼簡單。學習本節內容後,相信老鐵們能用Python擼起大家那龐大的Oracle數據庫了。Well,下面開始進入主題!
python


分析步驟以下sql


1. 瞭解源端和目標端的用戶信息數據庫

2. Oracle數據庫配置信息
bash

3. Python主機配置服務器

4. Python測試鏈接Oracle數據庫oracle



瞭解源端和目標端的用戶信息app


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

-- 目標數據庫的用戶信息
[grid@RACZJ-DDB.example.com]/home/grid$id grid
uid=302(grid) gid=301(oinstall) groups=301(oinstall),302(dba),304(asmadmin),305(asmdba),306(asmoper)

[oracle@RACZJ-DDB.example.com]/home/oracle$id oracle
uid=301(oracle) gid=301(oinstall) 01(oinstall),302(dba),303(oper),304(asmadmin),305(asmdba)


Oracle數據庫配置信息tcp


1.  查看數據庫服務器的IP地址ide

[grid@RACZJ-DDB.example.com]/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.  查看監聽服務oop

[grid@RACZJ-DDB.example.com]/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/tiger@192.168.117.100: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數據庫是否是很簡單呢?若是有疑惑的話,能夠後臺諮詢我喔!最後,很是感謝您的閱讀!

相關文章
相關標籤/搜索