通过DBI从Access到R的连接

时间:2017-09-27 22:18:48

标签: r ms-access

我希望分析笔记本电脑上Access数据库中包含的R(使用dplyr)中的数据。 (我第一次尝试在R中设置数据库连接。)

查看tidyverse站点,让dplyr处理Access数据,似乎连接必须通过DBI包(而不是RODBC)。

我正在努力学习dbConnect的语法。

我的RODBC代码是

base1<-odbcDriverConnect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=[filepath]/AdventureWorks DW 2012.accdb")

我(失败)尝试DBI是

DB <- dbConnect(drv=Microsoft Access Driver (*.mdb, *.accdb)), host=[filepath]/AdventureWorks DW 2012.accdb)

我做错了什么?

(我正在使用Windows 10 - 一切都是64位。)

2 个答案:

答案 0 :(得分:3)

我最近需要将我的RODBC定义的数据库连接转换为等效的DBI连接。这是原始的RODBC功能:

connect_to_access_rodbc <- function(db_file_path) {
   require(RODBC)
   # 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 <- odbcDriverConnect(db_connect_string)

   return(myconn)
}

正如here所解释的那样,dbplyr包是从DBI包构建的。 DBI::dbConnect()的第一个参数必须是适当的后端驱动程序。请参阅链接以获取驱动程序列表。对于Access,odbc::odbc()驱动程序是合适的。 dbConnect函数的第二个参数是前一个odbcDriverConnect调用中使用的完整连接字符串。考虑到这一点,以下功能应该连接到您的访问数据库:

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)
}

odbc包文档也提供了一个更细微的例子: https://github.com/r-dbi/odbc#odbc

答案 1 :(得分:-2)

我几天前就用过这个。

library(RODBC)

# for 32 bit windows
# Connect to Access db
# channel <- odbcConnectAccess("C:/Users/Excel/Desktop/Coding/Microsoft Access/Northwind.mdb")

# Get data
# data <- sqlQuery( channel , paste ("select * from Name_of_table_in_my_database"))


# for 64 bit windows
channel <- odbcDriverConnect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:/Users/Excel/Desktop/Coding/Microsoft Access/Northwind.mdb")

data <- sqlQuery( channel , paste ("select * from CUSTOMERS"))

odbcCloseAll()
相关问题