简体   繁体   English

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

[英]Python sqlalchemy trying to write pandas dataframe to SQL Server using .to_sql

I have a python code through which I am getting a pandas dataframe "df". 我有一个python代码,通过它我可获得熊猫数据框“ df”。 I am trying to write this dataframe to Microsoft SQL server. 我正在尝试将此数据帧写入Microsoft SQL Server。 I am trying to connect through the following code by I am getting an error 我正在尝试通过以下代码连接,但出现错误

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')

However at the engine.connect() line I am getting the following error 但是,在engine.connect()行中,出现以下错误

sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSN nor SERVER keyword supplied (0) (SQLDriverConnect)')

Can anyone tell me what I am missing. 谁能告诉我我所缺少的。 I am using Microsoft SQL Server Management Studio - 14.0.17177.0 我正在使用Microsoft SQL Server Management Studio-14.0.17177.0

I connect to the SQL server through the following 我通过以下方式连接到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

I am new to databases and python. 我是数据库和python的新手。 Kindly let me know if you need any additional details. 请让我知道是否需要其他详细信息。 Any help will be greatly appreciated. 任何帮助将不胜感激。 Thank you in advance. 先感谢您。

I was finally able to make it run. 我终于能够使它运行。

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)

Thanks to @gord-thompson who answered Here 感谢@ gord-thompson 在这里回答

Although my in my sql server, all the tables are under the 'dbo' schema (ie dbo.Test1, dbo.Other_Tables) and this query puts my table in 'sdcc\\neils' schema (ie sdcc\\neils.Test1, sdcc\\neils.Other_Tables) any solution to this? 虽然我在SQL Server中,但所有表都在“ dbo”架构下(即dbo.Test1,dbo.Other_Tables),并且此查询将我的表置于“ sdcc \\ neils”架构下(即sdcc \\ neils.Test1,sdcc \\ neils.Other_Tables)对此有什么解决方案?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM