Python sqlalchemy尝试使用.to_sql将pandas数据帧写入SQL Server

时间:2017-11-20 22:31:21

标签: python sql-server pandas sqlalchemy

我有一个python代码,通过它我得到一个pandas数据帧“df”。我试图将此数据帧写入Microsoft SQL Server。我试图通过以下代码连接我收到错误

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 type: Database Engine
Server name: bidept
Authentication: Windows Authentication

for which I log into my windows using username : sdcc\neils
and password : neil!pass

我是数据库和python的新手。如果您需要任何其他细节,请告诉我。任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

我终于能够让它运行了。

import pyodbc
from sqlalchemy import create_engine
import urllib

params = urllib.quote_plus(r'DRIVER={SQL Server};SERVER=bidept;DATABASE=BIDB;Trusted_Connection=yes')
### For python 3.5: urllib.parse.quote_plus 
conn_str = 'mssql+pyodbc:///?odbc_connect={}'.format(params)
engine = create_engine(conn_str)
reload(sys)
sys.setdefaultencoding('utf8')

df.to_sql(name='Test',con=engine, if_exists='append',index=False)

感谢@ gord-thompson回答Here

虽然我在我的sql server中,所有的表都在'dbo'模式下(即dbo.Test1,dbo.Other_Tables),这个查询将我的表放在'sdcc \ neils'模式中(即sdcc \ neils.Test1) ,sdcc \ neils.Other_Tables)对此有什么解决方法吗?