[英]Personal Database Connection Package in R
I have created a package to simplify the process of establishing a database connection when I begin a new project in R. Nearly every project requires me to connect to a proprietary database, which means looking back into files and copy-pasting in what I had done before and copying the sql drivers into the new project folder. 我创建了一个程序包,以简化在R中开始新项目时建立数据库连接的过程。几乎每个项目都需要我连接到专有数据库,这意味着要回顾文件并进行复制粘贴。之前,将sql驱动程序复制到新项目文件夹中。 Ideally I would like to start a new project with the following code:
理想情况下,我想使用以下代码开始一个新项目:
library(MyConnections)
conn <- MyConnections::get_conn()
I have a package function that works for database connections that does not require me to read a driver file. 我有一个用于数据库连接的打包功能,不需要我读取驱动程序文件。
get_mysql_conn <- function(){
require(RMySQL)
dbConnect(MySQL(),
user = 'user',
password = "password",
dbname = 'dbname',
host= 'host')
}
However, I cannot figure out how to make this code work the way that I want. 但是,我无法弄清楚如何使此代码以我想要的方式工作。
get_mssql_conn <- function(){
require(RJDBC)
driver <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver", "./drivers/mssql-jdbc-7.0.0.jre8.jar")
dbConnect(driver, "[connection string]",'[user]')
}
I assume there must be a way to create the driver object in the package and use it in the function in place of reading the file, but I am entirely lost as to how I go about that. 我认为必须有一种方法可以在包中创建驱动程序对象,并在函数中使用它来代替读取文件,但是我完全不知道该如何处理。 Any help or a pointing in the correct direction would be much appreciated.
任何帮助或指向正确方向的帮助将不胜感激。
You can create a directory inst/drivers
and save the .jar file there, then create your function as below: 您可以创建一个目录
inst/drivers
并在其中保存.jar文件,然后按如下所示创建函数:
get_mssql_conn <- function(){
driver <- RJDBC::JDBC(
"com.microsoft.sqlserver.jdbc.SQLServerDriver",
system.file("drivers", "mssql-jdbc-7.0.0.jre8.jar", package = "MyConnections")
)
RJDBC::dbConnect(driver, "[connection string]",'[user]')
}
Side note: you should never use require
or library
in an R package -- always use ::
and list the package in the Imports in the DESCRIPTION
file. 旁注: 永远不要在R包中使用
require
或library
-始终使用::
并在DESCRIPTION
文件的Imports中列出该包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.