三个步骤:
Step 1-创建ODBC数据源;
Step 2-install.packages('RODBC') ;
Step 3-编写连接测试脚本
(1)创建ODBC数据源
控制面板->系统和安全->管理工具->ODBC数据源(64位)->系统DSN,点击添加按钮,
接着选择安装数据源驱动程序 SQL Server,点击完成
填写名称和服务器,名称用于R连接需要用到的database,比如这里填入myData,
sqlserver的服务器名可以在登陆sqlserver的可视化界面那里找到
接着用户身份连接sqlserver
点击【测试数据源】
测试成功之后,完成创建ODBC数据源,继续下一步!
(2)在RStudio的Console,install.packages('RODBC')
> install.packages('RODBC') Installing package into ‘C:/Users/lmei/Documents/R/win-library/3.5’ (as ‘lib’ is unspecified) trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.5/RODBC_1.3-15.zip' Content type 'application/zip' length 879575 bytes (858 KB) downloaded 858 KB package ‘RODBC’ successfully unpacked and MD5 sums checked The downloaded binary packages are in C:\Users\lmei\AppData\Local\Temp\Rtmp6Fwdfk\downloaded_packages
(3)编写R脚本,ConnectSqlServer.R(‘myData’为第一步创建ODBC数据源时填写的名称),代码如下,运行代码
library('RODBC') myConn <- odbcConnect('myData',uid='sa',pwd='123456') count = sqlQuery(myConn,"select count(*) from tb_test") print(count)
console输出
library('RODBC') myConn<-odbcConnect('myData',uid='sa',pwd='123456') count = sqlQuery(myConn,"select count(*) from tb_test") print(count)