我想在 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")
这不起作用,我收到如下错误消息:
Error in new_result(connection@ptr, statement) : nanodbc/nanodbc.cpp:1344: 42000: [Microsoft][ODBC Microsoft Access Driver] Syntax error in CREATE TABLE statement.
有谁知道这意味着什么以及我如何才能让它发挥作用?
最佳答案
您首先检查文件是否存在是正确的,因为据我所知,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
然后您可以使用 RODBC
包中的 sqlSave()
函数在复制的空白 Microsoft Access 数据库中创建新表:
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)
关于sql - 使用 R 在 MS Access 数据库中创建新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51393448/