Python SQL Injection safe

Short question: I want to make my code safer but in this line it crashes:

self.cursor.execute("SELECT device_name FROM device WHERE device_id = %s", self.device_id)

This is working fine, but not safe for injection attacks:

self.cursor.execute("SELECT device_name FROM device WHERE device_id = " + str(self.device_id))

I have no idea, whats wrong in the first line.

[...] raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): Unknown error

Upvotes: 0

Views: 149

Answers (1)

orangecat
orangecat

Reputation: 246

The second argument must be a collection (tuple, list or dict) of parameters.

self.cursor.execute("SELECT device_name FROM device WHERE device_id = %s", 
                    (self.device_id,))

Upvotes: 1

Related Questions