Python mysql using variable to select a certain field

后端 未结 1 2013
暗喜
暗喜 2021-01-15 21:36

Having a little tricky issue with python and mysql. To keep it simple, the following code returns whatever is in the variable \'field\', which is a string. Such as \'usernam

相关标签:
1条回答
  • 2021-01-15 22:07

    Your query is actually formed as:

    select "field" from users where id="value"
    

    which returns you a string "field" instead of the actual table field value.

    You cannot parameterize column and table names (docs):

    Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.

    Use string formatting for that part:

    options = [userID]
    query = 'select {field} from users where id=(?)'.format(field=field)
    cursor.execute(query, options).fetchall()
    

    Related threads with some more explanations:

    • pysqlite: Placeholder substitution for column or table names?
    • Python MySQLdb: Query parameters as a named dictionary
    0 讨论(0)
提交回复
热议问题