MacOS环境下,通过 R 连接 sqlserver

Mac环境安装 sqlserver 看这篇文章

https://blog.csdn.net/ianly123/article/details/80824694

通过 R 连接 sqlserver 等数据库,重要的是配置 odbc 驱动和驱动数据源,在 mac 环境下,使用 unixODBC 配合 freeTDS 实现。

Install unixODBC

brew update
brew install unixodbc

Install freeTDS

brew install freetds --with-unixodbc

安装好之后查看配置

odbcinst -j

$ odbcinst -j
unixODBC 2.3.7
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /Users/ianly/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

配置相关配置文件

vim /usr/local/etc/freetds.conf

[MYMSSQL]
host = 127.0.0.1
port = 1401
tds version = 8.0
client charset = UTF-8

vim /usr/local/etc/odbc.ini

[mytest]
Driver=/usr/local/lib/libtdsodbc.so
Trace=No
Server=127.0.0.1
Port=1401
TDS_Version=8.0
Database=mhga002

测试连接

测试odbc驱动
$ isql mytest sa 1234qwer!
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
SQL>

R通过 RODBC 连接 sqlserver

在 R 环境中安装 RODBC 包

install.packages(“RODBC”, type = “source”)

然后测试连接

> library("RODBC")
> bcp <- odbcConnect("mytest", uid="sa", pwd="1234qwer!")
> bcp

#看到这些信息
#RODBC Connection 1
#Details:
#  case=nochange
#  DSN=mytest
#  UID=sa
#  PWD=******

# 试一下查询
lcbd <- sqlQuery(bcp, "SELECT * FROM PERSON")

# 看看得到了什么?
dim(lcbd)

#> [1] 919  14

OK!!

附:
设置镜像源命令:

options(repos=structure(c(CRAN=“https://mirrors.tuna.tsinghua.edu.cn/CRAN/”)))

你可能感兴趣的:(笔记,R)