Python mysql using variable to select a certain field

懵懂的女人 提交于 2019-12-19 11:35:52

问题


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 'username' or 'password'.

options = [field, userID]
entries = cursor.execute('select (?) from users where id=(?)', options).fetchall()
print(entries);

This code works correctly if I remove the first (?) and just use the actually name (like 'username') instead. Can anyone provide some input?


回答1:


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


来源:https://stackoverflow.com/questions/31751380/python-mysql-using-variable-to-select-a-certain-field

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