使用带有字符列的rodbcext

时间:2017-11-29 23:41:24

标签: r rodbc

我需要做一个批量插入,我在这里看:

MS-SQL Bulk Insert with RODBC

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)

该示例仅插入了数字列。我有数字和字符。知道如何为数字和字符列插入添加功能吗?

1 个答案:

答案 0 :(得分:0)

我很幸运使用参数化查询,数据框和一些字符串格式。这里是我使用的函数,它是通用的,并且具有明确的命名空间以保证函数的清晰度:

library(RODBCext)  # Also loads RODBC as dependency
Connection <- RODBC::odbcConnect('DSN')  # I am assuming you can connect via RODBC

BulkUpload <- function(new_data) {

  # Get the column names for the new data to add
  columns <- colnames(new_data)

  # Get the valid column names from the SQL target table 
  sql_columns <- RODBC::sqlColumns(Connection, "target_table")$COLUMN_NAME

  # Check to make sure all the columns in the dataframe are valid target table columns
  if(sum(columns %in% sql_columns) != length(columns)){
    stop("Cannot complete upload-- One or more columns doesn't exist in target table")
  }

  # Generate the query dynamically based upon the column names and number of columns
  column_query <- paste(columns, collapse = ",")
  values_query <- paste(rep("?", length(columns)), collapse = ",")
  NewDataQuery <- sprintf("INSERT INTO target_table (%s) VALUES (%s)", column_query, values_query)

  # Make the parameterized query call, given there is no information to add
  ifelse(nrow(new_data) == 0, stop("No new data to add"),
         RODBCext::sqlExecute(Connection, NewDataQuery, new_data))
}

这很好,因为它只会将数据插入到您在数据框列名中指定的列中。请注意,您需要确保您的数据框包含数据库中所需的任何数据字段的列,因为它们不是空的,并且没有默认值。