0

I want to add data from a Pandas DataFrame to SQL. I have tried to use .tosql() but if I use if_exists='append', index = True it will add even if a row with same index already exists.

Does anyone know how to add the data if the index is not already there and replace the existing data if there is already a same index.

Here is my code:

mydb = sqlite3.connect("test.db")
mycursor = mydb.cursor()
data = # the dataframe
data.to_sql(table_name, mydb, if_exists='append', index = True)
mydb.commit()
mydb.close()

here is the sample data I'm trying to add: https://jpst.it/2nFvu

Thanks in advance.

1 Answer 1

1

Can we try the below code:

    data.to_sql(table_name, mydb, if_exists='replace', index = False)
Sign up to request clarification or add additional context in comments.

3 Comments

I need the index as it the row title. So, I can't set it to False
Have you tried setting it to True instead?
Yes, but it is adding the duplicates instead of replacing the existing values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.