[英]Batch downloading of table using cx_oracle
我需要使用 cx_oracle 將一個大表從 oracle 數據庫下載到 python 服務器中。 但是,ram 在 python 服務器上受到限制,因此我需要以批處理方式進行。
我已經知道通常如何做整張桌子
usr = ''
pwd = ''
tns = '(Description = ...'
orcl = cx_Oracle.connect(user, pwd, tns)
curs = orcl.cursor()
printHeader=True
tabletoget = 'BIGTABLE'
sql = "SELECT * FROM " + "SCHEMA." + tabletoget
curs.execute(sql)
data = pd.read_sql(sql, orcl)
data.to_csv(tabletoget + '.csv'
我不確定該怎么做,但要一次加載一批 10000 行,然后將其保存到 csv 中,然后重新加入。
您可以直接使用 cx_Oracle 來執行此類批處理:
curs.arraysize = 10000
curs.execute(sql)
while True:
rows = cursor.fetchmany()
if rows:
write_to_csv(rows)
if len(rows) < curs.arraysize:
break
如果您使用的是 Oracle Database 12c 或更高版本,您還可以使用 OFFSET 和 FETCH NEXT ROWS 選項,如下所示:
offset = 0
numRowsInBatch = 10000
while True:
curs.execute("select * from tabletoget offset :offset fetch next :nrows only",
offset=offset, nrows=numRowsInBatch)
rows = curs.fetchall()
if rows:
write_to_csv(rows)
if len(rows) < numRowsInBatch:
break
offset += len(rows)
此選項不如第一個有效,並且涉及為數據庫提供更多工作要做,但根據您的情況,它可能對您更好。
這些例子都沒有直接使用熊貓。 我對那個包不是特別熟悉,但是如果您(或其他人)可以適當地調整它,希望這會有所幫助!
你可以像這樣實現你的結果。 在這里,我正在將數據加載到 df。
import cx_Oracle
import time
import pandas
user = "test"
pw = "test"
dsn="localhost:port/TEST"
con = cx_Oracle.connect(user,pw,dsn)
start = time.time()
cur = con.cursor()
cur.arraysize = 10000
try:
cur.execute( "select * from test_table" )
names = [ x[0] for x in cur.description]
rows = cur.fetchall()
df=pandas.DataFrame( rows, columns=names)
print(df.shape)
print(df.head())
finally:
if cur is not None:
cur.close()
elapsed = (time.time() - start)
print(elapsed, "seconds")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.