以下 pyodbc 连接工作正常:
import pyodbc
import pandas as pd
conn = pyodbc.connect(Driver='SQL Server',
Server='some_server_address,1433',
Database='some_db',
UID ='some_user',
PWD = 'some_password')
cursor = conn.cursor()
df = pd.read_sql_query('''select top 100 * from tableA''', conn)
cursor.close()
conn.close()
当我尝试使用 SQLalchemy 进行相同操作时,它失败了
from sqlalchemy.engine import URL
from sqlalchemy import create_engine
import sqlalchemy as sa
connection_string = "DRIVER={SQL Server};SERVER=some_server_address,1433;DATABASE=some_db;UID=some_user;PWD=some_password"
connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})
engine = create_engine(connection_url)
conn = engine.connect()
出现以下错误:
InterfaceError: (pyodbc.InterfaceError) ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'some_user'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'some_user'. (18456)")
(Background on this error at: https://sqlalche.me/e/20/rvf5)
我该如何修复它?
更新 正如下面的建议我尝试过
import pyodbc
import pandas as pd
connection_string = "DRIVER={SQL Server};SERVER=some_server_address,1433;DATABASE=some_db;UID=some_user;PWD=some_password"
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
df = pd.read_sql_query('''select top 100 * from tableA''', conn)
cursor.close()
conn.close()
一切都很顺利
您在 SQLAlchemy 中遇到了错误。此处已报道:
https://github.com/sqlalchemy/sqlalchemy/issues/11250
作为解决方法,您可以将单独的 kwargs 与
URL.create()
结合使用,类似于您对 .pyodbc.connect()
所做的操作:
import sqlalchemy as sa
engine = sa.create_engine(
sa.URL.create(
"mssql+pyodbc",
username="howie",
password="ab+cd",
host="192.168.0.199",
port=1433,
database="test",
query=dict(driver="SQL Server"),
)
)