SQL Server RODBC连接

时间:2011-04-19 17:51:41

标签: r rodbc

是否有人使用连接字符串示例来使用RODBC并连接到MS SQL Server 2005或2008。

谢谢。

5 个答案:

答案 0 :(得分:95)

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

答案 1 :(得分:8)

取自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)

答案 2 :(得分:1)

尝试使用RSQLS包:https://github.com/martinkabe/RSQLS

非常快速地将数据从data.frame推送到SQL Server或从SQL Server拉到data.frame。

示例:

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)

此解决方案比 RODBC :: sqlSave DBI :: dbWriteTable 更快,更强大。

答案 3 :(得分:1)

如果必须包含用户名和密码:

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)

答案 4 :(得分:0)

首先您必须创建/配置DSN(与特定数据库的ODBC连接)

然后安装RODBC库。

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

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