I'm currently using the RODBC package in R to run queries against SQL Server databases. Knitr now has the ability to use SQL code chunks (using the DBI package). I'd like to take advantage of this, as it allows me to have clean SQL embedded in my RMarkdown (RMD) document. However, I'm running into trouble getting DBI to connect to my SQL Server environment.
I've looked through DBI's help file, and vignettes, but am at a loss. They mention RSQLServer for SQL Server, but it has been pulled from CRAN. I'm aware I could install it from gitHub, using devtools, but I would prefer not relying on packages that can't be kept up on CRAN. I'd also prefer to avoid the RJDBC connector, as I've heard of reliability issues, and it makes the code that much less portable.
While my goal is to use this in RMD files, the below code is a simple R Script to keep the example as minimal as possible.
Does anyone know how to get the DBI example working in a similar fashion to the RODBC example?
# *** Query - edit table name to work with your db
my_query = "select top 100 * from my_table"
# *** This code works ***
library(RODBC)
# Replace <<SERVER>> and <<DB>> with your server and database, respectively
SQLServer <- odbcDriverConnect(connection = "Driver={SQL Server};server=<<SERVER>>;database=<<DB>>;trusted_connection=yes")
sqlResult <- sqlQuery(SQLServer, my_query)
# *** This code doesn't ***
library(DBI)
# Replace <<SERVER>> and <<DB>> with your server and database, respectively
SQLServer <- dbConnect(dbDriver("ODBC"), "server=<<SERVER>>;database=<<DB>>;trusted_connection=yes")
sqlResult <- dbSendQuery(con, my_query)