将Python(Pandas)数据框写入SQL数据库时出错。

7
我将尝试将一个Python数据框架放到MS SQL数据库中,但是我遇到了以下错误。 函数
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)

错误

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

你使用的pandas版本是什么? - joris
1个回答

21

在pandas 0.14之前,仅支持mysql和sqlite(默认为sqlite),从未支持过SQL server(这就是你得到的错误)。但是从pandas 0.14开始,支持将数据帧写入MS SQL Server。
但要使用它,您必须使用sqlalchemy引擎(请参见文档),而不是一个pyobdc连接对象。例如:

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

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


4
我收到了 "'Engine' object has no attribute 'cursor'" 的提示。 - Areza
2
我有完全相同的问题;使用Engine对象会抛出“无游标”错误,而使用raw_connection()则会抛出“sqlite master”错误。 - CutePoison
@CutePoison,你能在 https://github.com/pandas-dev/pandas/issues/ 上开一个问题吗? - joris
我刚刚弄清楚了,如果我使用“Driver={ODBC Driver 17 for SQL Server}”就可以正常工作。 - CutePoison

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接