Writing Python Dataframe to MSSQL Table

本小妞迷上赌 提交于 2019-12-11 14:43:54

问题


I currently have a Python dataframe that is 23 columns and 20,000 rows.

Using Python code, I want to write my data frame into a MSSQL server that I have the credentials for.

As a test I am able to successfully write some values into the table using the code below:

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

cursor = connection.cursor()

for index, row in df_EVENT5_15.iterrows():
    cursor.execute("INSERT INTO MODREPORT(rowid, OPCODE, LOCATION, TRACKNAME)

cursor.execute("INSERT INTO MODREPORT(rowid, location) VALUES (?,?)", (5, 'test'))
connection.commit()

But how do I write all the rows in my data frame table to the MSSQL server? In order to do so, I need to code up the following steps in my Python environment:

  1. Delete all the rows in the MSSQL server table

  2. Write my dataframe to the server


回答1:


When you say Python data frame, I'm assuming you're using a Pandas dataframe. If it's the case, then you could use the to_sql function.

df.to_sql("MODREPORT", connection, if_exists="replace")

The if_exists argument set to replace will delete all the rows in the existing table before writing the records.




回答2:


I realise it's been a while since you asked but the easiest way to delete ALL the rows in the SQL server table (point 1 of the question) would be to send the command

TRUNCATE TABLE Tablename

This will drop all the data in the table but leave the table and indexes empty so you or the DBA would not need to recreate it. It also uses less of the transaction log when it runs.



来源:https://stackoverflow.com/questions/48152944/writing-python-dataframe-to-mssql-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!