簡體   English   中英

Python mysql使用變量選擇某個字段

[英]Python mysql using variable to select a certain field

python和mysql有一點棘手的問題。 為簡單起見,以下代碼返回變量“field”中的任何內容,它是一個字符串。 例如“用戶名”或“密碼”。

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

如果我刪除第一個 (?) 並只使用實際名稱(如“用戶名”),則此代碼可以正常工作。 任何人都可以提供一些輸入嗎?

您的查詢實際上形成為:

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

它返回一個字符串“字段”而不是實際的表字段值。

您不能參數化列名和表名( docs ):

參數占位符只能用於插入列值。 它們不能用於 SQL 的其他部分,例如表名、語句等。

對該部分使用字符串格式:

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

相關主題以及更多解釋:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM