Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to an SQL server database in R

I'm trying to connect to the SQL Sever database using R but not sure on the details for the query string. I normally use SQL server management studio on SQL Server 2008 and connnect using single sign on. I found the below example

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

I get the below warning message

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

How do I go about finding the specifics i need?

like image 868
user1605665 Avatar asked Nov 12 '15 23:11

user1605665


2 Answers

I have done this in the past with an odbc named connection that I've already had in place. In case you don't know, you can create one in windows by typing into the search prompt 'odbc' and selecting "set up data sources". For example - if you named an odbc connection 'con1' you can connect the following way:

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


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


close(con)
like image 95
Jason Avatar answered Sep 25 '22 17:09

Jason


This works for me.

library(RODBC)
dbconnection <- odbcDriverConnect("Driver=ODBC Driver 11 for SQL Server;Server=server_name; Database=table_name;Uid=; Pwd=; trusted_connection=yes")
initdata <- sqlQuery(dbconnection,paste("select * from MyTable;"))
odbcClose(channel)

Also, see these links. RODBC odbcDriverConnect() Connection Error

https://www.simple-talk.com/sql/reporting-services/making-data-analytics-simpler-sql-server-and-r/

like image 43
ASH Avatar answered Sep 24 '22 17:09

ASH