Hvis vi antager, at R-datarammekolonner er nøjagtig de samme kolonner og i samme rækkefølge i Oracle (ikke mere eller mindre), så overvej anvend
at indsætte
med kollaps alle værdier i hver række:
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)
Og endnu bedre tilgang er at bruge parameterisering med RODBCext
hvor du bare sender den originale dataramme uden loop:
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)