我已经搜索了很多解决方案,但仍然在解决这个问题。
我正在尝试连接到在 127.0.0.1:1433 上运行的 SQL Server 实例。但是,我收到 sqlalchemy.exc.DBAPIError 并显示以下错误消息:
sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)")
我认为我需要安装 ODBC 驱动程序,但我不确定是否需要将其安装在 SQL Server Docker 映像上或我的本地 VM 上。如果答案是 Docker 映像,那么我认为我的 /etc/odbcinst.ini 文件配置正确,如下所示:
[ODBC Driver 17 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.10.so.2.1
UsageCount=1
但是如果需要在我的本地虚拟机上安装 ODBC 驱动程序,那么我的 /etc/odbcinst.ini 文件是空的。
这是我用来连接到 SQL Server 实例的 Python 代码:
from sqlalchemy import create_engine
server = "127.0.0.1,1433"
user = "sa"
password = "Pass@12345"
db_name = "test_database"
engine = create_engine(f'mssql+pyodbc://{user}:{password}@{server}/{db_name}?driver=ODBC Driver 17 for SQL Server')
connection = engine.connect()
print("connected")
还有一个问题是如果密码中有
@
我该怎么办?
sqlserver:2022-latest
docker 镜像,运行于 127.0.0.1:1433
任何帮助将不胜感激。谢谢!
通过以下步骤解决:
if ! [[ "18.04 20.04 22.04 22.10" == *"$(lsb_release -rs)"* ]];
then
echo "Ubuntu $(lsb_release -rs) is not currently supported.";
exit;
fi
sudo su
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list > /etc/apt/sources.list.d/mssql-release.list
exit
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql18
# optional: for bcp and sqlcmd
sudo ACCEPT_EULA=Y apt-get install -y mssql-tools18
echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bashrc
source ~/.bashrc
# optional: for unixODBC development headers
sudo apt-get install -y unixodbc-dev
注意:DNS 过滤可能会导致安装过程中出现问题
@
from sqlalchemy import create_engine
from urllib.parse import quote_plus
server = "127.0.0.1:1433"
user = "sa"
password = "Pass@12345"
db_name = "test_database"
dsn = "ODBC Driver 18 for SQL Server"
engine = create_engine(f"mssql+pyodbc://{user}:%s@{server}/{db_name}?TrustServerCertificate=yes&driver={dsn}" % quote_plus(password))
connection = engine.connect()
print("connected")