I'm trying to save records in an SQL Server database via Python and KEY is a primary key. Below is my Python code: -
import pyodbc
cnxn_str = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+db+';UID='+user+';PWD='+password_db)
cursor = cnxn_str.cursor()
for index, row in dataframe.iterrows():
cursor.execute("INSERT INTO Table(USER,SENDER,RECEIVER,DAY,ORIGIN,KEY) values(?,?,?,?,?,?)",
row.USER,row.SENDER,row.RECEIVER,row.DAY,row.ORIGIN,row.KEY)
cnxn_str.commit()
cursor.close()
The SQL in the code saves dataframe rows in the database table. However, I'm interested in modifying the above code to save records as per these conditions. In case row.KEY matches any record in the table, it should update it with current dataframe values. If there is no match, then an insertion should suffice. How can I modify this code to match meet this requirement?