Python讀寫oracle資料庫

來源:互聯網
上載者:User

標籤:sql函數   編碼   taf   pytho   預設   安裝   china   ora   index   

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

1. 所需Python工具庫

   cx_Oracle,pandas,可以使用通過控制台使用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, 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)

 

Python讀寫oracle資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.