Connecting to MS SQL Server from R on Mac/Linux

笑着哭i 提交于 2019-11-30 08:46:38
Meng Zhao

I've been struggling for a while on this. Here's what I found.

  1. Download from here -- Microsoft JDBC driver for SQL server
  2. Unzip the file, where you will find sqljdbc4.jar.
  3. Use:

    drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver", "<wherever sqljdbc4.jar is>")
    

This should work.

If i'm right, the idea is that for the PATH variable in drv function, one will need to specify the PATH where the JDBC driver is located (so if none, then downloaded it FIRST). Otherwise, one shall receive the common class not find error.

The following code achieves your goal of connecting to R from Mac OS x. Download the Microsoft JDBC driver from Microsoft here

Link to Gist / Code in Github

# install.packages("RJDBC",dep=TRUE)
library(RJDBC)
drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver" , "/Users/johndacosta/Downloads/sqljdbc_4.0/enu/sqljdbc4.jar" ,identifier.quote="`")
conn <- dbConnect(drv, "jdbc:sqlserver://192.172.1.210:55158;databaseName=master", "sa", "password")
d <- dbGetQuery(conn, "select * from sys.databases where database_id <= 4 ")
summary(d)

I had the exact same problem. This is a jTDS solution:

  1. Download jTDS 1.2.8 and unzip it. Say it is saved at ~/Downloads/jtds-1.2.8-dist/jtds-1.2.8.jar. Note: Other versions may not work!
  2. From R, set up driver: drv <- JDBC("net.sourceforge.jtds.jdbc.Driver", "~/Downloads/jtds-1.2.8-dist/jtds-1.2.8.jar").
  3. Set connection object: conn <- dbConnect(drv, "jdbc:jtds:sqlserver://servername:port;DatabaseName=databasename", domain="windows domain", user="user", password="pwd").

Here the field domain was messing things up. You can't put domain\username as your user. You have to define them separately according to the jTDS driver implementation.

I had this problem with jtds-1.3.1 on Linux. The problem disappeared when I tried switching to jtds-1.2.7. It appears there is something in jtds-1.3.* which makes it incompatible with RJDBC.

 library(RJDBC) 
 cp <- c
 ( 
      "<usr path>/jdbc/mdb/log4j.jar", 
      "<usr path>/jdbc/mdb/commons_lang.jar", 
      "<usr path>/jdbc/mdb/commons_logging.jar" 
  ) 

 .jinit(classpath=cp) 

 drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver",
        "/Users/victor/Downloads/sqljdbc_3.0/enu/sqljdbc4.jar") 
Madcat

Same error happened to me earlier when I was trying to use RJDBC to connect to Cassandra, it was solved by putting the Cassandra JDBC dependencies in your JAVA ClassPath.

See this answer:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!