Funk Pigeon
Funk Pigeon

Reputation: 168

MySQL delete query doesn't execute

I want to check for duplicate contacts and remove them from the user's contact list. There is no error message, it simply doesn't execute. Why doesn't it work?

cmd = "DELETE FROM contacts WHERE contact LIKE '{0}'.format(str(contact_))"
print(cmd)
# DELETE FROM contacts WHERE contact LIKE 'Ilovecake'
cur.execute(cmd)
conn.commit()
conn.close()

Upvotes: 0

Views: 355

Answers (2)

davidism
davidism

Reputation: 127180

You are vulerable to SQL injection attacks. Never format query strings directly, always use parameterized queries.

Your query currently matches contacts that are equal to contact_, but your use of LIKE implies that you want to match contacts that contain that value. Use wildcards in the query.

cur.execute('delete from contacts where contact like ?', ('%{}%'.format(contact_),))

The placeholder may be different depending on the dbapi driver you're using. You can use Flask-SQLAlchemy/SQLAlchemy to normalize parameter substitution as well as manage the connection and session automatically.

Upvotes: 1

Johan
Johan

Reputation: 118

if you are doing a kind of search you should use (I GUESS):

"DELETE FROM blabla WHERE contact LIKE '%what i am searching%'"

which allows text before and after the searched string, apply to your code

Upvotes: 0

Related Questions