Programing

SQL Server RODBC Connection

lottogame 2020. 12. 24. 23:20
반응형

SQL Server RODBC Connection


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

Thank you.


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

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)

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.


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)

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)

ReferenceURL : https://stackoverflow.com/questions/5720508/sql-server-rodbc-connection

반응형