0

I have a MySQL table in which every row contains a 'Date' value. I want to delete all the rows where the date is unequal to the current date. I tried using the following lines to do so:

date = time.strftime('%Y-%m-%d')

mycursor.execute("DELETE FROM " + League + " WHERE Date != " + "'" + date + "'")

It runs fine, but it doesn't actually delete any rows, even though I am sure there are rows with different dates. How can I delete these rows?

2
  • 2
    sql not equal is <> if I am not wrong, also you need to commit the transaction, also don't use string concatenation, it is prone to SQL injection Commented Aug 23, 2021 at 15:28
  • @Epsi95 Simply adding a commit statement worked. Thank you! How would you get rid of the concatenation? I have this right now: ` mycursor.execute("DELETE FROM %s WHERE Date <> %s", (League, Date)) ` But it gives a syntax error. Commented Aug 24, 2021 at 12:05

1 Answer 1

1

your code seems to be fine. What is League? Hope it's a variable for your table name! Also, use bind variables and avoid using string concatenations.

date = time.strftime('%Y-%m-%d')
print(date)

conn = database.create_db_connection()
cursor = conn.cursor()

query = "DELETE FROM test WHERE date != %s"
cursor.execute(query, date)
conn.commit()
Sign up to request clarification or add additional context in comments.

Comments

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.