Python mysql使用变量选择特定字段 [英] Python mysql using variable to select a certain field

查看:574
本文介绍了Python mysql使用变量选择特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python和mysql有一些棘手的问题.为简单起见,以下代码返回变量"field"(字符串)中的任何内容.例如用户名"或密码".

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?

推荐答案

您的查询实际上是这样构成的:

Your query is actually formed as:

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

它返回一个字符串"field"而不是表的实际字段值.

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

您无法参数化列名和表名( docs ):

参数占位符只能用于插入列值.他们 不能用于SQL的其他部分,例如表名, 声明等.

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

有关更多说明的线程:

  • pysqlite: Placeholder substitution for column or table names?
  • Python MySQLdb: Query parameters as a named dictionary

这篇关于Python mysql使用变量选择特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆