我是Python和SQL Server的新手。在过去的2天中,我一直在尝试将PANDAS DF插入我们的数据库中,没有任何运气。任何人都可以帮我调试错误吗?
我尝试了以下
import pyodbc
from sqlalchemy import create_engine
engine = create_engine('mssql+pyodbc:///?odbc_connect=DRIVER={SQL Server};SERVER=bidept;DATABASE=BIDB;UID=sdccneils;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
i通过以下
连接到SQL ServerServer type: Database Engine
Server name: bidept
Authentication: Windows Authentication
for which I log into my windows using username : sdccneils
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文档中所述,"使用传递精确的pyodbc字符串"时必须逃脱这些定界符。
所以,这将失败...
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)