SQL Server RODBC Connection

RRodbc

R Problem Overview


Does anyone have a connection string example for using RODBC and connecting to MS SQL Server 2005 or 2008.

Thank you.

R Solutions


Solution 1 - R

library(RODBC)
dbhandle <- odbcDriverConnect('driver={SQL Server};server=mysqlhost;database=mydbname;trusted_connection=true')
res <- sqlQuery(dbhandle, 'select * from information_schema.tables')

Solution 2 - R

Taken from a posting to r-help:

 library(RODBC)
 channel <- odbcDriverConnect("driver=SQL Server;server=01wh155073")
 initdata<- sqlQuery(channel,paste("select * from  test_DB .. 
 test_vikrant"))
 dim(initdata)
 odbcClose(channel)

Solution 3 - R

If you have to include the USERNAME and PASSWORD:

library(RODBC) # don't forget to install it beforehand

my_server="ABC05"
my_db="myDatabaseName"
my_username="JohnDoe"
my_pwd="mVwpR55zobUldrdtXqeHez"


db <- odbcDriverConnect(paste0("DRIVER={SQL Server};
                                 server=",my_server,";
                                 database=",my_db,";
                                 uid=",my_username,";
                                 pwd=",my_pwd))


sql="SELECT * FROM dbo.MyTableName" #dbo is the schema here
df <- sqlQuery(db,sql)

Solution 4 - R

Try to use RSQLS package: https://github.com/martinkabe/RSQLS

Very fast pushes data from data.frame to SQL Server or pulls from SQL Server to data.frame.

Example:

library(devtools)
install_github("martinkabe/RSQLS")
library(RSQLS)

cs <- set_connString("LAPTOP-USER\\SQLEXPRESS", "Database_Name")
push_data(cs, dataFrame, "dbo.TableName", append = TRUE, showprogress = TRUE)
df <- pull_data(cs, "SELECT * FROM dbo.TableName", showprogress = TRUE)

This solution is much faster and more robust than RODBC::sqlSave or DBI::dbWriteTable.

Solution 5 - R

First You have to Create/configure DSN (ODBC connection with specific DB)

Then install RODBC library.

library(RODBC)
myconn <-odbcConnect("MyDSN", uid="***", pwd="*******")

fetchData<- sqlQuery(myconn, "select * from tableName")
View(fetchData)
close(myconn)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrandonView Question on Stackoverflow
Solution 1 - RHenricoView Answer on Stackoverflow
Solution 2 - RIRTFMView Answer on Stackoverflow
Solution 3 - RIboView Answer on Stackoverflow
Solution 4 - RmateskabeView Answer on Stackoverflow
Solution 5 - RMukesh PandeyView Answer on Stackoverflow