首页 > 解决方案 > 使用 R 在 MS Access 数据库中创建新表

问题描述

我想在 MS Access 数据库中创建一个新表。我只是在处理一个虚拟示例,我现在将“mtcars”数据集添加到其中,抱歉这不是真正可重现的,但也许有一个简单的解决方案:

connect_to_access_dbi <- function(db_file_path)  {
  require(DBI)
  # make sure that the file exists before attempting to connect
  if (!file.exists(db_file_path)) {
    stop("DB file does not exist at ", db_file_path)
  }
  # Assemble connection strings
  dbq_string <- paste0("DBQ=", db_file_path)
  driver_string <- "Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
  db_connect_string <- paste0(driver_string, dbq_string)
  
  myconn <- dbConnect(odbc::odbc(),
                      .connection_string = db_connect_string)
  return(myconn)
}

# get to Access database(s) through research drive path
db_file_path <- 'Z:/American Kestrel projects/Idaho banding data/American Kestrels_2018_May15.accdb'

# connect to database
con <- connect_to_access_dbi(db_file_path)

data(mtcars)

# add new mtcars table
dbWriteTable(con, "mtcars", mtcars)
dbReadTable(con, "mtcars")

这不起作用,我收到如下错误消息:

new_result(connection@ptr, statement) 中的错误: nanodbc/nanodbc.cpp:1344: 42000: [Microsoft][ODBC Microsoft Access Driver] CREATE TABLE 语句中的语法错误。

有谁知道这意味着什么以及我如何才能完成这项工作?

标签: sqlrodbcdbi

解决方案


您首先检查文件是否存在是对的,因为据我所知,R 无法创建新的 Access 数据库。Base R 的file.create()功能就像它可以的那样,但是当您尝试在 Access 中打开它时,会出现一个弹出窗口,说它不是一个有效的数据库(因此,R 也无法写入它)。

我的解决方法是在我的计算机上的某处创建一个空白的 .accdb 文件,然后使用 R 的内置文件管理功能将其复制、重命名,并在我想导出到 Access 时将其移动到我的工作目录:

blank_db <- "C:/Users/JohnDoe/Desktop/foo.accdb" #a valid but empty Access database, previously created outside of R
db_file_path <- "Z:/American Kestrel projects/Idaho banding data/American Kestrels_2018_May15.accdb"

if (!file.exists(db_file_path)) file.copy(blank_db, db_file_path) #copies, renames, and moves empty Access data base to target path

sqlSave()然后,您可以使用包中的函数在复制的空白 Microsoft Access 数据库中创建新表RODBC

data(mtcars)
cars1 <- mtcars
cars2 <- mtcars

library(RODBC)
db <- odbcConnectAccess2007(db_file_path)
sqlSave(db, cars1, tablename = "MTCARS 1", fast = TRUE, safer = FALSE, rownames = FALSE, colnames = FALSE)
sqlSave(db, cars2, tablename = "MTCARS 2", fast = TRUE, safer = FALSE, rownames = FALSE, colnames = FALSE)
odbcClose(db)

推荐阅读