【解决方案】Mac环境Python连接SQL Server报错(pyodbc缺少ODBC驱动程序)

✨报错提示

Traceback (most recent call last):
  File "/Users/saber/Code/AAA/Python_Test_Project/2024-4-28/GenerateSQL.py", line 1, in <module>
    import pyodbc
ImportError: dlopen(/opt/homebrew/Caskroom/miniconda/base/envs/Python_Test_Project/lib/python3.8/site-packages/pyodbc.cpython-38-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/unixodbc/lib/libodbc.2.dylib
  Referenced from: <C588DC09-9A57-3093-AB08-56B2EC078195> /opt/homebrew/Caskroom/miniconda/base/envs/Python_Test_Project/lib/python3.8/site-packages/pyodbc.cpython-38-darwin.so
  Reason: tried: '/opt/homebrew/opt/unixodbc/lib/libodbc.2.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/unixodbc/lib/libodbc.2.dylib' (no such file), '/opt/homebrew/opt/unixodbc/lib/libodbc.2.dylib' (no such file)

Process finished with exit code 1

✨解决方案

阅读报错提示可知pyodbc缺少unixodbc

解决方案如下

brew install unixodbc

安装后报错提示如下

Traceback (most recent call last):
  File "/Users/saber/Code/AAA/Python_Test_Project/2024-4-28/GenerateSQL.py", line 13, in <module>
    conn = pyodbc.connect(conn_str)
pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/homebrew/lib/libmsodbcsql.17.dylib' : file not found (0) (SQLDriverConnect)")

实际上还缺少 Microsoft ODBC 驱动

使用brew安装

brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
brew install msodbcsql17

安装完成后 可以运行以下命令来检查 ODBC 驱动是否成功安装

odbcinst -j

这个命令将显示 ODBC 驱动的安装位置和配置文件的路径。


➜  ~ odbcinst -j
unixODBC 2.3.12
DRIVERS............: /opt/homebrew/etc/odbcinst.ini
SYSTEM DATA SOURCES: /opt/homebrew/etc/odbc.ini
FILE DATA SOURCES..: /opt/homebrew/etc/ODBCDataSources
USER DATA SOURCES..: /Users/saber/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

根据命令回显可以知道驱动配置文件位于 /opt/homebrew/etc/odbcinst.ini

使用如下命令行查看配置文件

cat /opt/homebrew/etc/odbcinst.ini
➜  ~ cat /opt/homebrew/etc/odbcinst.ini
[ODBC Driver 17 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/opt/homebrew/lib/libmsodbcsql.17.dylib
UsageCount=2

此时重新运行Python脚本

已经可以正常通过pyodbc连接SQL Server


✨参考及引用

https://stackoverflow.com/questions/48904183/import-pyodbc-failure-mac-os


⭐转载请注明出处

本文作者:双份浓缩馥芮白

原文链接: https://www.cnblogs.com/Flat-White/p/18163974

版权所有,如需转载请注明出处。

posted @ 2024-04-28 16:24  双份浓缩馥芮白  阅读(233)  评论(0编辑  收藏  举报