Max00355
Max00355

Reputation: 867

Fixing SQL Injection With _mysql

I just found out that the way I am using _mysql is causing a major SQL Injection problem.

My current code looks like:

db = _mysql.connect('', 'user', 'pass', 'db')
query = """SELECT * FROM stuff WHERE thing="{0}" """.format(user_input)
cur.query(query)

What am I doing wrong and how can I fix it so that it is safe?

I have tried using _mysql.escape_string() but that still returns an SQL syntax error.

Upvotes: 0

Views: 1200

Answers (2)

Robert H
Robert H

Reputation: 11730

A nice handy reference is available via the bobby tables website.

You may also find value in In this powerpoint reference which shows some examples of sql injection as well as possible ways to mitigate the issue.

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191749

You can use MySQLdb on its own:

conn = MySQLdb.connect();
curs = conn.cursor();
curs.execute("SELECT * FROM stuff WHERE thing = %s", (user_input));

If you want to stick with _mysql, use db.escape_string(user_input).

Documentation: http://mysql-python.sourceforge.net/MySQLdb.html

Upvotes: 2

Related Questions