python excel导入oracle数据库_【Python代替Excel】12:Python操作oracle数据库
日常工作中,如果有數(shù)據(jù)庫權(quán)限,那么在oracle中提取數(shù)據(jù)、在Python中處理是比較方便的。Python也提供了一個(gè)庫專門操縱數(shù)據(jù)庫。今天就專門來講講如何在Python中操作數(shù)據(jù)庫。
準(zhǔn)備工作
需要工具:oracle、PL/SQL、Python
import cx_Oracle
如果用anaconda prompt直接安裝的話,可能會(huì)出現(xiàn)錯(cuò)誤。最好在網(wǎng)站cx-Oracle下載對應(yīng)版本(我下載的如下):
下載好之后,直接點(diǎn)擊安裝包按照提示安裝即可。然后在anaconda里import。
SQL語言
先來復(fù)習(xí)一下幾個(gè)簡單的sql語句吧:
select * from table1 #查詢table1的所有數(shù)據(jù)
create table test_table( name varchar(20), score number) #創(chuàng)建表test_table,包含name、score兩列
insert into test_table(name,score) values('zoe',80) #插入一行數(shù)據(jù)
連接&操作數(shù)據(jù)庫連接數(shù)據(jù)庫
import cx_Oracle
import os
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.UTF8' #設(shè)置語言環(huán)境
db = cx_Oracle.connect('username','password','database') #連接數(shù)據(jù)庫 用戶名、密碼、數(shù)據(jù)庫名
cursor = db.cursor()
connect里填的,如下:創(chuàng)建表
create_table = """
create table py_table(
name varchar(20),
score number
)
""" #字符串里寫SQL語句,用三個(gè)雙引號括起來
create_flag = cursor.execute(create_table) #執(zhí)行該SQL語句
運(yùn)行完這兩句,可以在數(shù)據(jù)庫里看到新的表(如果沒有,可能要刷新或者重啟一下數(shù)據(jù)庫)。插入數(shù)據(jù)
insert_data1 = """
insert into py_table(name,score) values('zoe',80)
"""
cursor.execute(insert_data1) #執(zhí)行SQL語句
db.commit() #提交插入多條數(shù)據(jù)
scores = {
'Tom':100,
'Lily':60,
'Emily':85
}
#第一種 循環(huán)
for i in scores.items(): #遍歷scores字典的鍵、值
cursor.execute('insert into py_table(name,score) values(:1,:2)',i) #i是一個(gè)元組,包含2個(gè)元素
#目前查到的方法,只能把所有列名寫出來,然后:1、:2、、、、傳入數(shù)據(jù)。
db.commit() #提交執(zhí)行
#第二種 多條插入
scores1 = [(i,n) for i,n in scores.items()]
cursor.executemany('insert into py_table values(:1,:2)',scores1) # scores1是列表,里面是元組
db.commit() #提交執(zhí)行
用executemany的速度會(huì)比第一種循環(huán)的要快,特別是數(shù)據(jù)多的時(shí)候。查詢數(shù)據(jù)
sql1 = cursor.execute('select * from py_table') #查詢數(shù)據(jù)
data1 = pd.DataFrame(sql1.fetchall()) #fetchall為取所有數(shù)據(jù)
data2 = sql1.fetchmany(10) #取10條數(shù)據(jù)綁定變量查詢
有時(shí)候查詢的條件是變化的,就需要用到綁定變量。
#查詢zoe的數(shù)據(jù)
sql = cursor.execute("""select * from py_table where name=:name""",name='zoe') #:name為綁定變量
data = sql.fetchall()
#in查詢
sql = cursor.execute("""select * from py_table where name in (:1,:2,:3)""",['zoe','Tom','Lily'])
data = sql.fetchall()
今天的連接Oracle數(shù)據(jù)庫學(xué)會(huì)了嗎?當(dāng)然還有連接Mysql數(shù)據(jù)庫,不過使用的庫不一樣,大家可以自行百度。
用Python插入數(shù)據(jù)庫的時(shí)候,一定要注意數(shù)據(jù)的格式,如果與Oracle表的字段格式不匹配,就會(huì)出錯(cuò)。
不過使用Python連接數(shù)據(jù)庫,最大的用處還是能方便在數(shù)據(jù)庫查詢數(shù)據(jù),并且直接在Python中編程處理清洗了。
專欄列表
總結(jié)
以上是生活随笔為你收集整理的python excel导入oracle数据库_【Python代替Excel】12:Python操作oracle数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 写入xml文件_java读写x
- 下一篇: python淘宝cookies抢购_Py