将python(pandas)数据框写入SQL数据库错误

Shi*_*dra 2 python sql sql-server pyodbc pandas

我试图将一个python数据框放到MS SQL DB,我收到以下错误

功能

def put_to_server(df):       # df is a pandas data frame
   server="KORNBSVM04\MSSQLSERVER2012"
   Driver="{SQL Server}"
   userid=''
   pswd=''
   cnxn = pyodbc.connect(driver=Driver, server=server, database="CIHOTLINE",uid=userid, pwd=pswd)
   cur=cnxn.cursor()
   df.to_sql(name='dbo.test',con=cnxn)
Run Code Online (Sandbox Code Playgroud)

错误

 File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 950, in to_sql
index_label=index_label)
File "C:\Python27\lib\site-packages\pandas\io\sql.py", line 475, in to_sql
index_label=index_label)
File "C:\Python27\lib\site-packages\pandas\io\sql.py", line 1084, in to_sql
index_label=index_label)
File "C:\Python27\lib\site-packages\pandas\io\sql.py", line 543, in __init__
if self.pd_sql.has_table(self.name):
File "C:\Python27\lib\site-packages\pandas\io\sql.py", line 1094, in has_table
return len(self.execute(query).fetchall()) > 0
File "C:\Python27\lib\site-packages\pandas\io\sql.py", line 1041, in execute
raise_with_traceback(ex)
File "C:\Python27\lib\site-packages\pandas\io\sql.py", line 1030, in execute
cur.execute(*args)
pandas.io.sql.DatabaseError: Execution failed on sql: SELECT name FROM sqlite_master WHERE type='table' AND name='dbo.test';
Run Code Online (Sandbox Code Playgroud)

jor*_*ris 10

在pandas 0.14之前从未支持过SQL服务器(只有mysql和sqlite,默认为sqlite.因此出现错误),但是从pandas 0.14开始,支持将数据帧写入MS SQL服务器.
但要使用它,您必须使用sqlalchemy 引擎(请参阅docs)而不是pyobdc连接对象.例如:

from sqlalchemy import create_engine
engine = create_engine('mssql+pyodbc://scott:tiger@mydsn')
df.to_sql('test', engine)
Run Code Online (Sandbox Code Playgroud)

请参阅关于此的pandas文档:http://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries

  • 我得到“‘引擎’对象没有属性‘光标’” (3认同)
  • 我有完全相同的问题;使用和 Engine 对象抛出“无游标”错误,使用 raw_connection() 抛出“sqlite master”错误 (2认同)