你如何使用RODBC连接到mssql服务器?

时间:2014-04-13 17:15:50

标签: r rodbc

我有一个Oracle数据库,我使用RODBC连接连接到oracle,如下所示:

library(RODBC)
new_sql<-c("select * from table")
tryCatch({
            ch=odbcConnect("odbc_con",pwd = "!passwd!")
            res<-sqlQuery(ch,new_sql)
            },error = function(e) {
            print(odbcGetErrMsg(ch))          
        })

数据库被镜像到mssql,我使用管理员工具使用DATA SOURCES(ODBC)创建了一个与mssql服务器的新odbc连接,名为new_odbc_con。

当我将代码更新为:

tryCatch({
            ch=odbcConnect("odbc_con",pwd = "!password!")
            res<-sqlQuery(ch,new_sql)
            },error = function(e) {
            print(odbcGetErrMsg(ch))          
        })

我无法连接到sql server并执行sql。我做错了什么?

2 个答案:

答案 0 :(得分:0)

如果它再次出现,这就是我为解决这个问题所采取的措施。

  1. 我使用管理工具(数据源(ODBC))
  2. 创建了系统odbc连接
  3. 我已将此行更新为ch=odbcConnect("odbc_con",pwd = "!password!") ch=odbcConnect("odbc_con",uid="userid",pwd = "!password!")
  4. 像魅力一样工作。

答案 1 :(得分:0)

还提供Linux redhat解决方案,在调用R中的dsn之前需要编辑以下3个配置文件

$ sudo nano /etc/odbc.ini 
[salesdb]
Driver=FreeTDS
Trace=No
Server=xxx
Port=1433
Database=xxxx
TDS_Version=8.0


$ sudo nano /etc/freetds.conf
# A typical Microsoft server
[salesdb]
    host = xxxx
    port = 1433
    tds version = 8.0
    client charset = UTF-8

$ sudo nano /etc/odbcinst.ini
# Driver from the FreeTDS package
# Setup from the unixODBC package
[FreeTDS]
Description     = FreeTDS
Driver          = /usr/lib64/libtdsodbc.so # this is the linux path, you can call odbcinst -q -d to see where the other drivers were installed in the system

最后,您可以使用tsql或isql来测试会话是否正确安装或者下面的命令,

$ odbcinst -q -s