How to insert a dataframe into a SQL Server table?

后端 未结 3 547
梦毁少年i
梦毁少年i 2020-12-05 05:29

I\'m trying to upload a dataframe to a SQL Server table, I tried breaking it down to a simple SQL query string..

library(RODBC)
con <- odbcDriverConnect(\         


        
相关标签:
3条回答
  • 2020-12-05 05:48

    Since insert INTO is limited to 1000 rows, you can dbBulkCopy from rsqlserver package.

    dbBulkCopy is a DBI extension that interfaces the Microsoft SQL Server popular command-line utility named bcp to quickly bulk copying large files into table. For example:

    url = "Server=localhost;Database=TEST_RSQLSERVER;Trusted_Connection=True;"
    conn <- dbConnect('SqlServer',url=url)
    ## I assume the table already exist
    dbBulkCopy(conn,name='T_BULKCOPY',value=df,overwrite=TRUE)
    dbDisconnect(conn)
    
    0 讨论(0)
  • 2020-12-05 05:50

    [edited] Perhaps pasting the names(df) would solve the scaling problem:

       values <- paste( " df[  , c(", 
                         paste( names(df),collapse=",") ,
                                       ")] ", collapse="" ) 
          values
          #[1] " df[  , c( a,b,c )] "
    

    You say your code is "working".. I would also have thought one would use sqlSave rather than sqlQuery if one wanted to "upload".

    I would have guessed this would be more likely to do what you described:

     sqlSave(con, df, tablename = "MyTable")
    
    0 讨论(0)
  • 2020-12-05 05:54

    This worked for me and I found it to be simpler.

    library(sqldf)
    library(odbc)
    con <- dbConnect(odbc(),
                     Driver = "SQL Server",
                     Server = "ServerName",
                     Database = "DBName",
                     UID = "UserName",
                     PWD = "Password")
    dbWriteTable(conn = con, 
                 name = "TableName", 
                 value = x)  ## x is any data frame
    
    0 讨论(0)
提交回复
热议问题