如何连接到R中的SQL Server数据库

时间:2015-11-12 23:04:45

标签: sql-server r rodbc

我尝试使用R连接到SQL Sever数据库,但不确定查询字符串的详细信息。我通常在SQL Server 2008上使用SQL server management studio并使用单点登录连接。我找到了下面的例子

myconn <- odbcDriverConnect(connection="Driver={SQL Server 
Native Client 11.0};server=hostname;database=TPCH;
trusted_connection=yes;")

我收到以下警告信息

Warning messages:
1: In odbcDriverConnect(connection = "Driver={SQL Server \nNative Client 11.0};server=hostname;database=TPCH;\ntrusted_connection=yes;") :
  [RODBC] ERROR: state IM002, code 0, message [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
2: In odbcDriverConnect(connection = "Driver={SQL Server \nNative Client 11.0};server=hostname;database=TPCH;\ntrusted_connection=yes;") :
  ODBC connection failed

如何找到我需要的细节?

5 个答案:

答案 0 :(得分:7)

我过去曾用过odbc命名连接完成了这项工作,我已经有了这个连接。如果您不知道,您可以通过在搜索提示中输入“odbc”来在Windows中创建一个&#39; odbc&#39;并选择&#34;设置数据源&#34;。例如 - 如果你命名了一个odbc连接&#39; con1&#39;您可以通过以下方式连接:

con<-odbcConnect('con1') #opening odbc connection


df<-sqlQuery(con, "select  *
                         from ssiD.dbo.HOURLY_SALES
                         ") #querying table


close(con)

答案 1 :(得分:3)

答案 2 :(得分:1)

问题比这更简单。最大的线索是错误消息中的\n。有些东西重新连接了你的连接字符串,现在驱动程序名称中有一个换行符。这与任何注册的驱动程序名称都不匹配。然后疼痛和痛苦随之而来。确保整个连接字符串都在一行!

我经常使用: driver={SQL Server Native Client 11.0}; ...

它的效果非常好。比依赖预先定义的连接名称要好得多。

答案 3 :(得分:1)

首先,您需要安装软件包“RSQLServer”及其所有依赖项。 然后在RStudio中执行以下命令,并带有相关参数:

conn <- DBI::dbConnect(RSQLServer::SQLServer(),
                 server = '<server>', 
                 port = '<port>',
                 properties = list(
                   user = '<user>',
                   password = '<password>'
                 ))

最后,db_list_tables(conn)为您提供相应数据库中的表列表。

答案 4 :(得分:1)

尝试其他ODBC驱动程序。 在Windows中按“窗口”按钮,然后键入“odbc”。 单击“数据源(ODBC)”链接。 转到“驱动程序”选项卡以查看SQL Server的可用驱动程序。 另外 - 删除连接字符串中分号后面的“”空格。 注 - 数据库属性应指向数据库名称而不是表名。

这对我有用:

odbcDriverConnect("Driver=SQL Server Native Client 11.0;Server=<IP of server>;Database=<Database Name>;Uid=<SQL username>;Pwd=<SQL password>")