Python MySQL, is this a prepared statement?

可紊 提交于 2021-01-29 12:38:44

问题


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,))

回答1:


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, i.e. 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.



来源:https://stackoverflow.com/questions/52014207/python-mysql-is-this-a-prepared-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!