1. 程式人生 > 資料庫 >Python讀寫及備份oracle資料庫操作示例

Python讀寫及備份oracle資料庫操作示例

本文例項講述了Python讀寫及備份oracle資料庫操作。分享給大家供大家參考,具體如下:

最近專案中需要用到Python呼叫oracle實現讀寫操作,踩過很多坑,歷盡艱辛終於實現了。效能怎樣先不說,有方法後面再調優嘛。現在把程式碼和注意點記錄一下。

1. 所需Python工具庫

cx_Oraclepandas,可以使用通過控制檯使用pip進行安裝(電腦中已經安裝)

2. 實現查詢操作

#工具庫匯入
import pandas as pd
import cx_Oracle
# 注:設定環境編碼方式,可解決讀取資料庫亂碼問題
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
#實現查詢並返回dataframe
def query(table)
  host = "127.0.0.1"  #資料庫ip
  port = "1521"   #埠
  sid = "test"  #資料庫名稱
  dsn = cx_Oracle.makedsn(host,port,sid)
  #scott是資料使用者名稱,tiger是登入密碼(預設使用者名稱和密碼)
  conn = cx_Oracle.connect("scott","tiger",dsn)
  #SQL語句,可以定製,實現靈活查詢
  sql = 'select * from '+ table
  # 使用pandas 的read_sql函式,可以直接將資料存放在dataframe中
  results = pd.read_sql(sql,conn)
  conn.close
  return results
test_data = query(test_table) # 可以得到結果集

3. 實現插入操作

#工具庫匯入
import pandas as pd
import cx_Oracle
#實現插入功能
def input_to_db(data,table):
  host = "127.0.0.1"  #資料庫ip
  port = "1521"   #埠
  sid = "test"  #資料庫名稱
  dsn = cx_Oracle.makedsn(host,dsn)
  #建立遊標
  cursor = connection.cursor()
  #sql語句,注意%s要加引號,否則會報ora-01036錯誤
  query = "INSERT INTO"+table+"(name,gender,age) VALUES ('%s','%s','%s')"
  #逐行插入資料
  for i in range(len(data)):
    name= data.ix[i,0]
    gender= data.ix[i,1]
    age= data.ix[i,2]
   # 執行sql語句
    cursor.execute(query % (name,age))
  connection.commit()
  # 關閉遊標
  cursor.close()
  connection.close()
#測試插入資料庫
#測試資料集
test_data = pd.DataFrame([['小明','男',18],['小芳','女',18]],index = [1,2],columns=['name','gender','age'])
#呼叫函式實現插入
input_to_db(test_data,test_table1)

4. Python備份Oracle資料庫

#!/usr/bin/python
#coding=utf-8
import threading
import os
import time
#使用者名稱
user = 'username'
#密碼
passwd = 'password'
#備份儲存路徑
savepath = '/home/oracle/orcl_bak/'
#要備份的表
tables = ' tables=department,employee'
#備份週期
circle = 2.0
#備份命令
global bak_command
bak_command = 'exp '+user+'/'+passwd + ' file=' + savepath
def orclBak():
  now = time.strftime('%Y-%m-%d %H:%M:%S')
  command = bak_command + now + '.dmp' + tables
  print command
  if os.system(command) == 0:
    print '備份成功'
  else:
    print '備份失敗'
  global t
  t = threading.Timer(circle,orclBak)
  t.start()
t = threading.Timer(circle,orclBak)
t.start()

更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python編碼操作技巧總結》、《Python資料結構與演算法教程》、《Python Socket程式設計技巧總結》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》

希望本文所述對大家Python程式設計有所幫助。