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

2024-03-30

我正在尝试将 python 数据框放入 MS SQL DB,但收到以下错误

FUNCTION

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)

ERROR

 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 引擎 (see docs http://docs.sqlalchemy.org/en/latest/core/engines.html) 而不是 pyodbc 连接对象。例如:

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 http://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 python (pandas) Dataframe 写入 SQL 数据库错误 的相关文章

随机推荐