Python:将Pandas数据帧写入MSSQL-->数据库E

2024-05-26 11:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据框,大约有20k行和20列。我想把它写到MSSQL中的一个表中。

我已成功建立连接:

connection = pypyodbc.connect('Driver={SQL Server};' 
                              'Server=XXX;' 
                              'Database=line;' 
                              'uid=XXX;' 
                              'pwd=XXX')

cursor = connection.cursor()

我正试图用以下代码将pandas数据帧写入MSSQL服务器:

df_EVENT5_16.to_sql('MODREPORT', connection, if_exists = 'replace')

但我得到了以下错误:

DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'.")


Tags: 数据namemasterpandassqlitesqlserverdriver
2条回答

不需要使用pyodbc来连接MSSQL,SQL Alchemy将为您做到这一点。 我们还可以直接将数据帧插入数据库,而无需使用to_sql()方法迭代数据帧。这是对我有用的代码-

# To insert data frame into MS SQL database without iterate the data-frame
import pandas as pd
from sqlalchemy import create_engine, MetaData, Table, select
from six.moves import urllib
params = urllib.parse.quote_plus("DRIVER={SQL 
Server};SERVER=serverName;DATABASE=dbName;UID=UserName;PWD=password")
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params) 
engine.connect() 
# suppose df is the data-frame that we want to insert in database
df.to_sql(name='table_name',con=engine, index=False, if_exists='append')

现代Pandas版本期望^{}作为连接,因此使用SQLAlchemy:

from sqlalchemy import create_engine

con = create_engine('mssql+pyodbc://username:password@myhost:port/databasename?driver=SQL+Server+Native+Client+10.0')

然后:

df_EVENT5_16.to_sql('MODREPORT', con, if_exists='replace')

来自DataFrame.to_sql() docs

con : SQLAlchemy engine or DBAPI2 connection (legacy mode)

Using SQLAlchemy makes it possible to use any DB supported by that library.

If a DBAPI2 object, only sqlite3 is supported.

相关问题 更多 >