我正在尝试将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)
错误
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 0.14之前从未支持过SQL Server(只有mysql和sqlite,默认是sqlite。因此会出现错误),但是从 Pandas 0.14开始支持将数据帧写入MS SQL Server。
但是要使用此功能,您必须使用 sqlalchemy引擎(请参阅docs)而不是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
关于python - 将python(pandas)数据框写入SQL数据库错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26055556/