与odbc一样与RJDBC连接

时间:2018-10-15 08:00:12

标签: r sql-server jdbc

我正在尝试使用RJDBC连接到我的MS SQL数据库,但我不知道该填写url参数。使用odbc,这就足够了:

dbConnect(odbc::odbc(),
          Driver = "SQL Server",
          dsn = "MyDsn",
          uid = "User",
          pwd = "123456",
          server = "myserver123456\\myserver1",
          database = "MyDatabase")

当我从odbc交换驱动程序到jdbc时,它失败了:

dbConnect(RJDBC::JDBC(classPath = "C:/jdbc/mssql-jdbc-7.0.0.jre8.jar"),
          Driver = "SQL Server",
          dsn = "MyDsn",
          uid = "User",
          pwd = "123456",
          server = "myserver123456\\myserver1",
          database = "MyDatabase")

错误:Error in .jcall("java/sql/DriverManager", "Ljava/sql/Connection;", "getConnection", : argument "url" is missing, with no default

我应该在url参数中写些什么?如何知道?

1 个答案:

答案 0 :(得分:1)

RJDBC对dbConnect函数使用不同的参数:驱动程序定义和连接URL(您缺少的部分)。例如(来自https://www.rforge.net/RJDBC/),要连接到MySQL数据库,您的代码应如下所示:

library(RJDBC)
drv <- JDBC("com.mysql.jdbc.Driver",
       "/etc/jdbc/mysql-connector-java-3.1.14-bin.jar",
       identifier.quote="`")
conn <- dbConnect(drv, "jdbc:mysql://localhost/test", "user", "pwd")
     

为MySQL加载JDBC驱动程序(根据需要调整驱动程序JAR文件的路径)并连接到本地数据库“ test”。连接句柄conn用于所有后续操作。

对于SQL Server,您的代码将类似于以下内容(来自https://www.r-bloggers.com/connecting-to-sql-server-from-r-using-rjdbc/):

require(RJDBC)
drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver",
            "C:/jdbc/mssql-jdbc-7.0.0.jre8.jar") 
conn <- dbConnect(drv, "jdbc:sqlserver://serverName", "userID", "password")