试图使用odbc
和sqlalchemy
连接到MS SQL Server数据库,以将pandas.DataFrame
写入数据库,并获得一个错误,似乎暗示使用的用户是一个空字符串(当提供一个连接字符串)。为什么这会?
相关代码段为:
import sqlalchemy
# setup db connection
server = 'myserver'
database = 'mydb'
table = 'mytable'
username = 'username'
password = 'password'
cnxn_str = 'DSN=MyMSSQLServer;DATABASE='+database+';UID='+username+';PWD='+password+';MultipleActiveResultSets=True;'
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % cnxn_str)
# testing connection
cnxn = engine.connect()
...
和(删节的)错误消息是:
---------------------------------------------------------------------------
InterfaceError Traceback (most recent call last)
<ipython-input-207-6807f223c9bb> in <module>()
15
16 #Sample select query
---> 17 cnxn = engine.connect()
18 result = connection.execute("SELECT @@version;")
19 for row in result:
/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py in connect(self, **kwargs)
2016 """
2017
-> 2018 return self._connection_cls(self, **kwargs)
2019
2020 def contextual_connect(self, close_with_result=False, **kwargs):
...
...
/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/strategies.py in connect(connection_record)
95 if connection is not None:
96 return connection
---> 97 return dialect.connect(*cargs, **cparams)
98
99 creator = pop_kwarg('creator', connect)
/home/mapr/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/default.py in connect(self, *cargs, **cparams)
383
384 def connect(self, *cargs, **cparams):
--> 385 return self.dbapi.connect(*cargs, **cparams)
386
387 def create_connect_args(self, url):
InterfaceError: (pyodbc.InterfaceError) ('28000', u"[28000] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user ''. (18456) (SQLDriverConnect)")
对我来说也很奇怪的是,同一连接字符串在使用同一SQL Server读取时在代码中成功工作,但是在这种情况下,使用cnxn = pyodbc.connect(cnxn_str)
来建立连接如果我想写信给SQLite3)。
谁能解释为什么会发生这种情况以及如何解决?谢谢。
尝试以更多的" SQL炼金术"方式进行操作:
# pyodbc
engine = sqlalchemy.create_engine('mssql+pyodbc://{}:{}@MyMSSQLServer'.format(username, password ))
或
# pymssql
engine = sqlalchemy.create_engine('mssql+pymssql://{}:{}@{}:{}/{}'.format(username, password, server, port, database))