我试图连接到MS SQL Server,所以我在具有驱动程序“ SQL Server Native Client 11.0”的服务器上创建了系统DSN。 DSN的名称是:
mydsn1
我只能使用SQL Server IP地址和SQL Server身份验证(使用登录ID和密码)进行连接。为此,我使用了ODBC数据源管理员GUI,甚至已经成功完成了“测试数据源”。
现在,我正在尝试使用SQL Alchemy在python中测试与SQL Server的连接。
import pyodbc
import sqlalchemy as sa
import urllib
driver='SQL Server Native Client 11.0'
server = '12.34.567.890'
database = 'MYDATABASE'
userid = 'Cool-USER'
password = 'P@ssword1!'
stringparams = "DRIVER={{{0}}};SERVER={1};DATABASE={2};UID={3};PWD={4}".format(driver, server, database, userid, password)
params = urllib.parse.quote_plus(stringparams)
myengine = sa.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
cursor = myengine.raw_connection().cursor()
cursor.execute('SELECT top 3 * FROM SOME_TABLE')
for row in cursor:
print(row)
cursor.commit()
cursor.close()
mystr = "mssql+pyodbc://{0}:{1}@{2}/{3}?driver={4}".format(userid, password, server, database, driver)
myengine = sa.create_engine(mystr)
cursor = myengine.raw_connection().cursor()
cursor.execute('SELECT top 3 * FROM SOME_TABLE')
for row in cursor:
print(row)
cursor.commit()
cursor.close()
我真正想要实现的是利用我创建的实际DSN! sqlalchemy中使用DSN的create_engine()
函数有语法吗?
我的理解是,由于我已经创建了DSN(通过在SQL身份验证中提供登录名和密码),因此在调用sa.create_engine()函数时,无需再次提供这些凭据。但是,不幸的是,我不断收到错误消息。
driver='SQL Server Native Client 11.0'
server = '12.34.567.890'
database = 'MYDATABASE'
userid = 'Cool-USER'
password = 'P@ssword1!'
dsn = 'mydsn1'
stringparams = "DRIVER={{{0}}};SERVER={1};DATABASE={2};DSN={3}".format(driver, server, database, dsn)
params = urllib.parse.quote_plus(stringparams)
myengine = sa.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
cursor = myengine.raw_connection().cursor()
我在cursor = myengine.raw_connection().cursor()
行出现以下错误
InterfaceError: (pyodbc.InterfaceError) ('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user ''. (18456) (SQLDriverConnect); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user ''. (18456)")
(Background on this error at: http://sqlalche.me/e/rvf5)
对此有任何帮助,我们将不胜感激!