Posts

Showing posts from August, 2010

Prevent sql injection in python using cursor.execute correctly

Today I did some searching about how to prevent sql injection while using Python and MySQLdb. Then I found some links with tips and also did some experiment and found something interesting. Usually I used to write mysql query in python this way: query = ".." cursor.execute(query) But it can't prevent sql injection. Check this example: (It will be better if you create a table named user_info with the fields: id, name, email and populate the table with some data.) import MySQLdb try: conn = MySQLdb.connect (host = "localhost", user = "uname", passwd = "pass", db = "mydb") cursor = conn.cursor() email = "' OR '1'='1" query = "SELECT * FROM user_info WHERE email = '" + email + "'" print query cursor.execute(query) if cursor.rowcount > 0: print cursor.fetchall() else: print "no item found" except