本文實例講述了Python讀寫及備份oracle數據庫操作。分享給大家供大家參考,具體如下:
最近項目中需要用到Python調用oracle實現讀寫操作,踩過很多坑,歷盡艱辛終于實現了。性能怎樣先不說,有方法后面再調優嘛。現在把代碼和注意點記錄一下。
1. 所需Python工具庫
	cx_Oracle,pandas,可以使用通過控制臺使用pip進行安裝(電腦中已經安裝)
2. 實現查詢操作
#工具庫導入import pandas as pdimport cx_Oracle# 注:設置環境編碼方式,可解決讀取數據庫亂碼問題import osos.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'#實現查詢并返回dataframedef 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 resultstest_data = query(test_table) # 可以得到結果集3. 實現插入操作
#工具庫導入import pandas as pdimport cx_Oracle#實現插入功能def input_to_db(data,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)  #建立游標  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,gender,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-8import threadingimport osimport time#用戶名user = 'username'#密碼passwd = 'password'#備份保存路徑savepath = '/home/oracle/orcl_bak/'#要備份的表tables = ' tables=department,employee'#備份周期circle = 2.0#備份命令global bak_commandbak_command = 'exp '+user+'/'+passwd + ' file=' + savepathdef 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程序設計有所幫助。
新聞熱點
疑難解答