Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # DB Handle for config file #
- dbhandle <- odbcDriverConnect()
- # save the data in the table finally
- sqlSave(dbhandle, bp, "FACT_OP", append=TRUE, rownames=FALSE, verbose = verbose, fast = TRUE)
- # varTypes <- c(Date="datetime", QueryDate = "datetime")
- # sqlSave(dbhandle, bp, "FACT_OP", rownames=FALSE,verbose = TRUE, fast = TRUE, varTypes=varTypes)
- # DB handle close
- odbcClose(dbhandle)
- toSQL = data.frame(...);
- write.table(toSQL,"C:\export\filename.txt",quote=FALSE,sep=",",row.names=FALSE,col.names=FALSE,append=FALSE);
- sqlQuery(channel,"BULK
- INSERT Yada.dbo.yada
- FROM '\\<server-that-SQL-server-can-see>\export\filename.txt'
- WITH
- (
- FIELDTERMINATOR = ',',
- ROWTERMINATOR = '\n'
- )");
- library(RODBC)
- channel <- ...
- dataTable <- ...relevant data...
- numberOfThousands <- floor(nrow(dataTable)/1000)
- extra <- nrow(dataTable)%%1000
- thousandInsertQuery <- function(channel,dat,range){
- sqlQuery(channel,paste0("INSERT INTO Database.dbo.Responses (IDNum,State,Answer)
- VALUES "
- ,paste0(
- sapply(range,function(k) {
- paste0("(",dat$IDNum[k],",'",
- dat$State[k],"','",
- gsub("'","''",dat$Answer[k],fixed=TRUE),"')")
- })
- ,collapse=",")))
- }
- if(numberOfThousands)
- for(n in 1:numberOfThousands)
- {
- thousandInsertQuery(channel,(1000*(n-1)+1):(1000*n),dataTable)
- }
- if(extra)
- thousandInsertQuery(channel,(1000*numberOfThousands+1):(1000*numberOfThousands+extra))
- library(DBI)
- library(RJDBC)
- library(tidyverse)
- # Specify where you driver lives
- drv <- JDBC(
- "com.microsoft.sqlserver.jdbc.SQLServerDriver",
- "c:/R/SQL/sqljdbc42.jar")
- # Connect to AWS RDS instance
- conn <- drv %>%
- dbConnect(
- host = "jdbc:sqlserver://xxx.ccgqenhjdi18.ap-southeast-2.rds.amazonaws.com",
- user = "xxx",
- password = "********",
- port = 1433,
- dbname= "qlik")
- if(0) { # check what the conn object has access to
- queryResults <- conn %>%
- dbGetQuery("select * from information_schema.tables")
- }
- # Create test data
- example_data <- data.frame(animal=c("dog", "cat", "sea cucumber", "sea urchin"),
- feel=c("furry", "furry", "squishy", "spiny"),
- weight=c(45, 8, 1.1, 0.8))
- # Works in 20ms in my case
- system.time(
- conn %>% dbWriteTable(
- "qlik.export.test",
- example_data
- )
- )
- # Let us see if we see the exported results
- conn %>% dbGetQuery("select * FROM qlik.export.test")
- # Let's clean the mess and force-close connection at the end of the process
- conn %>% dbDisconnect()
Add Comment
Please, Sign In to add comment