Mac(M1芯片)下用R/RStudio连接SQL Server数据库报错求助
问题:Mac M1环境下R连接SQL Server报错的解决
环境与背景
- 系统:Macbook Pro(M1芯片)
- 背景:统计/生物信息领域出身,对网络、服务器、数据库相关知识了解有限
已执行操作
终端安装驱动命令
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release brew update HOMEBREW_NO_ENV_FILTERING=1 ACCEPT_EULA=Y brew install msodbcsql18 mssql-tools18
第一次R连接尝试及报错
R代码
library(DBI) library(odbc) con <- DBI::dbConnect(odbc::odbc(), Driver = "ODBC Driver 18 for SQL Server", Server = "xxx.xxx.xxx.xx", Database = "Dbname", UID = "username", PWD = "password", Port = 3306, .connection_string ="TrustServerCertificate=yes")
报错信息
Error: nanodbc/nanodbc.cpp:1021: 00000: [unixODBC][Driver Manager]Data source name not found and no default driver specified
第二次R连接尝试及报错
R代码
con <- DBI::dbConnect(odbc::odbc(), .connection_string = "Driver={ODBC Driver 18 for SQL Server};Uid=username;Pwd=password;Host=xxx.xxx.xxx.xx;Port=3306;Database=Dbname;TrustServerCertificate=yes;")
报错信息
Error: nanodbc/nanodbc.cpp:1021: 00000: [Microsoft][ODBC Driver 18 for SQL Server]Neither DSN nor SERVER keyword supplied [Microsoft][ODBC Driver 18 for SQL Server]Invalid connection string attribute
疑问解答与解决建议
1. 第二个错误中的Server Keyword是什么?服务器是否应填写IP地址?
- Server Keyword指的是连接字符串里的
Server参数,SQL Server ODBC驱动只识别Server,不识别Host(后者是MySQL等数据库的参数)。 - 服务器地址可以填写IP,格式需注意:若端口非默认值,可写成
IP地址,端口(例如xxx.xxx.xxx.xx,3306),也可分开指定Server=IP;Port=端口。
2. ODBC驱动的选择是否重要?如何确认使用的驱动正确?
- 驱动选择非常关键,不同版本(如ODBC Driver 17/18)的语法、支持特性存在差异,必须与已安装的驱动版本完全匹配。
- 确认驱动的方法:
- 终端执行命令:
odbcinst -q -d,查看输出中是否存在ODBC Driver 18 for SQL Server。 - R中执行代码:
odbc::odbcListDrivers(),查看可用驱动列表,确保代码中填写的Driver名称与列表完全一致(注意大小写、空格)。
- 终端执行命令:
3. dbConnect()的参数是否存在错误?
- 第一次尝试的问题:
- 可能是驱动名称不匹配,或unixODBC未正确识别驱动;另外SQL Server默认端口为1433,你使用的3306是MySQL默认端口,需先确认目标SQL Server的实际端口。
- 同时混合了独立参数与
.connection_string的写法,容易导致参数冲突。
- 第二次尝试的问题:
- 错误使用
Host替代Server,SQL Server驱动不识别该参数,因此提示缺少SERVER keyword。
- 错误使用
最终解决步骤
- 确认SQL Server端口:先联系数据库管理员确认目标SQL Server的端口,默认是1433,若使用3306需确认是否为自定义配置。
- 验证驱动安装:执行
odbcinst -q -d,确保输出包含[ODBC Driver 18 for SQL Server]。 - 修改R连接代码,推荐两种正确写法:
写法一(独立参数):
写法二(完整连接字符串):library(DBI) library(odbc) con <- DBI::dbConnect(odbc::odbc(), Driver = "ODBC Driver 18 for SQL Server", Server = "xxx.xxx.xxx.xx", # 非默认端口写成"xxx.xxx.xxx.xx,3306" Database = "Dbname", UID = "username", PWD = "password", TrustServerCertificate = "yes")con <- DBI::dbConnect(odbc::odbc(), .connection_string = "Driver={ODBC Driver 18 for SQL Server};Server=xxx.xxx.xxx.xx,3306;Database=Dbname;Uid=username;Pwd=password;TrustServerCertificate=yes;")
内容的提问来源于stack exchange,提问作者haymourt
相关产品推荐
相关产品推荐

