简体   繁体   中英

Python MySQL, is this a prepared statement?

I am setting up a mysql app. This is my getUsername method connects using standard mysqldb formatting. Does this mean it is a prepared statement? Also, is this code safe, or am I vulnerable to SQL injection?

def selectUser(userName):
    try:
        username = pickle.loads(base64.decode(userName))
    except:
        username = "admin"
    query = "SELECT name FROM users WHERE name = '%s'"
    conn = MySQLdb.connect('localhost', 'dbAdmin', 'lja8j30lJJal##', 'blog');
    with conn:
        c = conn.cursor()
        c.execute(query, (username,))

No - there is no way to make a prepared statement in MySQLdb. You won't find any mysql_stmt_init() , mysql_stmt_prepare() or mysql_stmt_execute() in the MySQL API binding in _mysql.c .

For whatever reason, the author of MySQLdb chose to simulate parameters instead of using real server-side prepared statements.

To protect against SQL injection, the MySQLdb package uses Python string-format syntax. It interpolates dynamic values into SQL queries and applies correct escaping, ie adding \\ before quote characters to make sure dynamic values don't contain string delimiters.

See my answer to How do PyMySQL prevent user from sql injection attack? for a demonstration.

However, escaping doesn't help if you need to use dynamic values for numeric constants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM