将Python Dataframe编写到MSSQL表

时间:2018-01-08 15:07:22

标签: python sql-server connection

我目前拥有一个23列和20,000行的Python数据帧。

使用Python代码,我想将我的数据帧写入我拥有凭据的MSSQL服务器。

作为测试,我能够使用以下代码成功地将一些值写入表中:

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()

但是如何将数据框表中的所有行写入MSSQL服务器?为此,我需要在Python环境中编写以下步骤:

  
      
  1. 删除MSSQL服务器表中的所有行

  2.   
  3. 将我的数据框写入服务器

  4.   

2 个答案:

答案 0 :(得分:0)

当你说Python数据框时,我假设您正在使用Pandas数据帧。如果是这种情况,那么您可以使用to_sql功能。

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

设置为 replace if_exists参数将在写入记录之前删除现有表中的所有行。

答案 1 :(得分:0)

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.