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. 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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.