2017-06-12 119 views
0

我有,例如數據幀:插入來自R數據框中多行到Oracle數據庫

df <- as.data.frame(matrix(sample(c(NA, 1:50), 49, replace = TRUE), 7)) 

它看起來像這樣:

V1 V2 V3 V4 V5 V6 V7 
1 46 6 23 7 22 42 1 
2 47 33 47 50 42 NA 49 
3 14 35 49 48 37 10 22 
4 42 23 5 4 41 46 48 
5 32 36 24 26 19 31 45 
6 26 47 28 19 34 19 32 
7 37 13 46 46 NA 22 49 

現在我想寫這個數據幀到Oracle數據庫無使用sqlSave,因爲我有一個巨大的data.frame和R Studio崩潰,如果我這樣做。相反,我決定用sqlquery的做到這一點:

library(RODBC) 
connHandle <- odbcConnect("DBName", uid="user", pwd="password") 
sqlQuery(connHandle, sprintf("INSERT INTO MYTABLE VALUES %s", stringWithMyDataframeValues)) 
close(connHandle) 

我已閱讀this後,但它並沒有爲我工作。

這樣做的最佳方式是什麼?我想要通過的字符串應該如何處理?提前致謝。

回答

1

假設ř數據幀列是完全相同的列和Oracle中相同的順序(未或多或少),考慮applypaste崩潰每一行中的所有值:

sqls <- sprintf("INSERT INTO MYTABLE VALUES (%s)", 
       apply(df, 1, function(i) paste(i, collapse=",")))  
sqls 
# [1] "INSERT INTO MYTABLE VALUES (2,10,9,50,34,37,29)" 
# [2] "INSERT INTO MYTABLE VALUES (7,24,33,21,21,20,3)" 
# [3] "INSERT INTO MYTABLE VALUES (39,38,2,33,43,33,7)" 
# [4] "INSERT INTO MYTABLE VALUES (30,11,33,1,29,26,11)" 
# [5] "INSERT INTO MYTABLE VALUES (50,45,13,27,3,35,36)" 
# [6] "INSERT INTO MYTABLE VALUES (41,5,39,17,5,22,5)" 
# [7] "INSERT INTO MYTABLE VALUES (21,50,39,30,2,11,49)" 

# RECOMMENDED APPROACH TO SPECIFY COLUMNS 
sqls <- sprintf("INSERT INTO MYTABLE (Col1, Col2, Col3, Col4, Col5, Col6, Col7) VALUES (%s)", 
       apply(df, 1, function(i) paste(i, collapse=","))) 

connHandle <- odbcConnect("DBName", uid="user", pwd="password") 
lapply(sqls, function(s) sqlQuery(connHandle, s)) 
close(connHandle) 

甚至更好的方法是使用RODBCext進行參數設置,您只需在原始數據幀中傳遞無迴路的參數:

library(RODBCext) 

connHandle <- odbcConnect("DBName", uid="user", pwd="password") 
query <- "INSERT INTO MYTABLE (Col1, Col2, Col3, Col4, Col5, Col6, Col7) VALUES (?, ?, ?, ?, ?, ?, ?)" 
sqlExecute(connHandle, query, df) 

odbcClose(connHandle)