使用odbc_connect从SQLAlchemy连接到SQL Server
作者:互联网
我是Python和SQL Server的新手.在过去的两天里,我一直在尝试将pandas df插入我们的数据库,但没有任何运气.谁能帮我调试错误.
我尝试了以下
import pyodbc
from sqlalchemy import create_engine
engine = create_engine('mssql+pyodbc:///?odbc_connect=DRIVER={SQL Server};SERVER=bidept;DATABASE=BIDB;UID=sdcc\neils;PWD=neil!pass')
engine.connect()
df.to_sql(name='[BIDB].[dbo].[Test]',con=engine, if_exists='append')
但是,在engine.connect()行中,出现以下错误
sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')
谁能告诉我我所缺少的.我正在使用Microsoft SQL Server Management Studio-14.0.17177.0
我通过以下方式连接到SQL Server
Server type: Database Engine
Server name: bidept
Authentication: Windows Authentication
for which I log into my windows using username : sdcc\neils
and password : neil!pass
我也尝试过
import pyodbc
conn_str = (
r'Driver={SQL Server Native Client 11.0};'
r'Server=bidept;'
r'Database=BIDB;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
df.to_sql(name='Test',con=cnxn, if_exists='append')
为此我得到了这个错误
pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)")
任何帮助将不胜感激,因为我不知所措.
解决方法:
如SQLAlchemy documentation中所述,使用传递的精确Pyodbc字符串时,“必须对转义符进行URL转义”.
因此,这将失败…
import pyodbc
from sqlalchemy import create_engine
params = r'DRIVER={SQL Server};SERVER=.\SQLEXPRESS;DATABASE=myDb;Trusted_Connection=yes'
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = create_engine(conn_str)
…但这会起作用:
import pyodbc
from sqlalchemy import create_engine
import urllib
params = urllib.parse.quote_plus(r'DRIVER={SQL Server};SERVER=.\SQLEXPRESS;DATABASE=myDb;Trusted_Connection=yes')
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = create_engine(conn_str)
标签:pandas,sqlalchemy,python,sql-server,pyodbc 来源: https://codeday.me/bug/20191025/1929411.html