【问题标题】:Python sqlalchemy trying to write pandas dataframe to SQL Server using .to_sqlPython sqlalchemy 尝试使用 .to_sql 将 pandas 数据帧写入 SQL Server
【发布时间】:2018-05-04 06:35:55
【问题描述】:

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

【问题讨论】:

标签: python sql-server pandas sqlalchemy


【解决方案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) 有什么解决办法吗?

【讨论】:

  • 解决方案df.to_sql(name='Test',con=engine, if_exists='append',index=False, schema="dbo")
猜你喜欢
  • 2021-03-02
  • 2015-08-18
  • 1970-01-01
  • 2014-07-23
  • 2018-11-29
  • 2020-10-25
  • 2018-01-23
  • 2016-02-22
  • 2017-08-01
相关资源
最近更新 更多