Python鏈接Oracle,安裝、基本用法

本文將介紹如何使用Python鏈接Oracle數據庫進行數據讀取與寫入。首先介紹環境的安裝,此部分借鑑網友的博客,後一部分介紹鏈接數據庫和讀書取數等基本使用語法。html

1. 環境安裝sql

借鑑網友闌珊的博客,感謝分享!數據庫

https://www.cnblogs.com/lansan0701/p/8039332.htmlapp

2. 使用語法函數

(1) 鏈接數據庫fetch

#加載cx_Oracle模塊
import cx_Oracle

#建立鏈接
conn = cx_Oracle.connect('用戶名/密碼@主機IP地址:端口號/數據庫名稱', encoding='utf-8')
cursor = conn.cursor()

(2) 查詢,讀取數據spa

需求:獲取表student中2019年度學生的姓名,年齡,性別,成績數據。code

# 首先寫好sql語句,這裏須要注意stat_year字段數據庫中的類型varchar,在Oracle中查詢條件爲stat_year = '2019',但在execute()方法中的sql字符串中不須要加引號
sql = 'select name,age,gender,grade from student where stat_year = 2019'

# 利用cousor對象的execute()方法執行sql語句
cursor.execute(sql)

#利用cursor對象的fetchall()方法獲取sql的結果返回類型爲list,其中每一個元素(每條記錄)爲元組類型
student_informations = cursor.fetchall()

需求:獲取符合必定篩選條件的記錄數orm

sql = 'select count(*) from student where stat_year = 2019'

# 利用cousor對象的execute()方法執行sql語句
cursor.execute(sql)

#利用cursor對象的fetchall()方法獲取sql的結果返回類型爲list,其中每一個元素(每條記錄)爲元組類型,獲取結果列表中第一個元組的第一個元素(實際上結果列表只有一個元組,元組中只有一個元素)
counts = cursor.fetchall()[0][0]

(3) 將數據批量寫入數據庫htm

需求:將若干條記錄寫入數據庫(已建立)中。這裏利用cursor.executemany()方法實現

name = ['A','B','C']
age = [10,8,9]
gender = ['m','f','m']
grade = [80,92,84]
stat_year = ['2019','2019','2019'] 

# 構造數據列表,每行記錄表示爲字典
data = []
for i in range(len(name)):
data.append({'name':name[i],'age':age[i],'gender':gender[i],'stat_year '=stat_year [i]})

# 利用executemany()函數將列表中的數據插入到數據庫中
cursor.executemany('insert into student values(:name ,:age ,:gender ,:grade,:stat_year )',data)
db.commit()

(4) 最後,記得關閉數據庫鏈接

cursor.close()
conn.close()
相關文章
相關標籤/搜索