SQLAlchemy 无法使用 SQL Server 的 ODBC 驱动程序 18 连接到 SQL Server,但 pyodbc 可以

问题描述 投票:0回答:1

我正在 Windows PC 上工作,无法使用 SQLAlchemy 连接到我的 Microsoft SQL 服务器。

我的登录凭据如下:IP、服务器名称、用户名、数据库、密码。

我无法使用 Windows 授权,因为我想全天定期从 r、pi 或云服务运行完成的脚本。

password = 'xxx'
server = os.environ['xxx']
database = os.environ['xxx']
username = os.environ['xxx']
driver='{ODBC Driver 18 for SQL Server}' #does not work with pyodbc if + used instead of {}

connection_string = f"mssql+pyodbc://{username}:{password}@{server}/{database}?driver={driver};Encrypt=False"

try:
    # Create the SQLAlchemy engine
    engine = create_engine(connection_string)
    
    # Test the connection
    with engine.connect() as connection:
        # Use the inspector to get table names
        inspector = inspect(connection)
        tables = inspector.get_table_names()
        
        # Print the list of tables
        print("Tables in the database:")
        for table in tables:
            print(table)

except Exception as e:
    print(f"Error connecting to the database: {e}")

我仅使用 pyodbc 就可以毫无问题地连接到服务器。

connection_string = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password};TrustServerCertificate=Yes;'

try:
    connection = pyodbc.connect(connection_string)
    print("Connection successful!")
    connection.close()
except Exception as e:
    print(f"Error connecting to the database: {e}")

尝试使用 SQLAlchemy 时,我会收到 08001、IM0002 或 IM0012 错误,具体取决于我对连接字符串所做的操作。

driver='{ODBC Driver 18 for SQL Server}'
中,我也尝试过用
+
代替带有和不带
{}

的空格

我也尝试过使用和不使用

TrustedServerCertificate=Yes/True
Encrypt=False/No

我预计 SQLAlchemy 会像 pyodbc 一样轻松连接,但我无法让它工作。

我也尝试了这里建议的方法。

完整错误:

连接数据库时出错:(pyodbc.Error) ('IM012', '[IM012] [Microsoft][ODBC Driver Manager] DRIVER 关键字语法错误 (0) (SQLDriverConnect)')

任何见解将不胜感激。

python sql-server windows sqlalchemy pyodbc
1个回答
1
投票

对于 SQLAlchemy 连接 URL,查询字符串分隔符是

&
,而不是
;
。另外,
Encrypt=False
无效,请使用
Encrypt=no

我通常建议人们使用

URL.create()
来构建他们的连接 URL:

import sqlalchemy as sa

connection_url = sa.engine.URL.create(
    "mssql+pyodbc",
    username="scott",
    password="tiger^5HHH",
    host="192.168.0.199",
    database="test",
    query={"driver": "ODBC Driver 18 for SQL Server", "Encrypt": "no"}
)

然后,如果您想查看隐藏密码的字符串化 URL,只需打印它即可。

print(connection_url)
"""
mssql+pyodbc://scott:***@192.168.0.199/test?Encrypt=no&driver=ODBC+Driver+18+for+SQL+Server
"""
© www.soinside.com 2019 - 2024. All rights reserved.