Python mysql 使用变量 select 某个字段
Python mysql using variable to select a certain field
python 和 mysql 有一个小问题。为简单起见,以下代码 returns 变量 'field' 中的任何内容,它是一个字符串。如'username'或'password'.
options = [field, userID]
entries = cursor.execute('select (?) from users where id=(?)', options).fetchall()
print(entries);
如果我删除第一个 (?) 并只使用实际名称(如 'username'),则此代码可以正常工作。谁能提供一些意见?
您的查询实际上形成为:
select "field" from users where id="value"
哪个 returns 你是一个字符串 "field" 而不是实际的 table 字段值。
您不能参数化列和 table 名称 (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.
对该部分使用字符串格式:
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 有一个小问题。为简单起见,以下代码 returns 变量 'field' 中的任何内容,它是一个字符串。如'username'或'password'.
options = [field, userID]
entries = cursor.execute('select (?) from users where id=(?)', options).fetchall()
print(entries);
如果我删除第一个 (?) 并只使用实际名称(如 'username'),则此代码可以正常工作。谁能提供一些意见?
您的查询实际上形成为:
select "field" from users where id="value"
哪个 returns 你是一个字符串 "field" 而不是实际的 table 字段值。
您不能参数化列和 table 名称 (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.
对该部分使用字符串格式:
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