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

2024-04-30

我有一个Python代码,通过它我得到了一个pandas数据框“df”。我正在尝试将此数据框写入 Microsoft SQL 服务器。我尝试通过以下代码进行连接,但出现错误

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 的新手。如果您需要任何其他详细信息,请告诉我。任何帮助将不胜感激。先感谢您。


我终于能够让它运行了。

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 https://stackoverflow.com/questions/47416699/need-help-writing-pandas-dataframe-into-sql-server-using-python

虽然我在我的sql服务器中,但所有表都在“dbo”模式下(即dbo.Test1,dbo.Other_Tables),并且此查询将我的表放在“sdcc\neils”模式中(即sdcc\neils.Test1,sdcc\ neils.Other_Tables)有什么解决方案吗?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python sqlalchemy 尝试使用 .to_sql 将 pandas 数据帧写入 SQL Server 的相关文章

随机推荐