簡體   English   中英

如何在python中的where子句中使用變量訪問sql

[英]How to use a variable in where clause in python to access sql

u=int(input('   ENTER YOUR CHOICE(1-6)  : '))

sql_select_Query = 'select * from hotel **where H_ID =u'**
mycur.execute (sql_select_Query)

dip=mycur.fetchall()
for x in dip:
   print(x,'\n')

出現錯誤 mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'u' in 'where clause'

從 PYTHON 開始,u 是用戶的輸入。 如何將其包含在 sql 的 where 子句中

您需要在查詢中使用占位符(對於 MySQL,通常是%s ),然后將變量分別傳遞給.execute()

u = int(input(' ENTER YOUR CHOICE(1-6) : ')) 
sql_select_Query = 'select * from hotel where H_ID = %s'

mycur.execute(sql_select_Query, (u,)) 
dip = mycur.fetchall()
for x in dip:
    print(x, '\n')

對我來說最簡單的方法是在字符串引號前放一個f ,比如

f"the result is {your_variable}"

在代碼編輯器中

不幸的是,這只適用於 >= python3.7。 但您也可以使用.format

"the result is {your_variable}".format(your_variable=0)

在代碼編輯器中

你的腳本是

sql_select_Query = f'select * from hotel where H_ID = {u}'

要么

sql_select_Query = 'select * from hotel where H_ID = {u}'.format(u=u)

暫無
暫無

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

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