亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Python中的mysql.execute()語句中使用變量(對象)

在Python中的mysql.execute()語句中使用變量(對象)

臨摹微笑 2023-08-08 14:59:22
我的 python 項目的以下代碼似乎不起作用import mysql.connector as sql??? ? cxn=sql.connect(user='adithyan',password='vinod123',database='workout2')??? ? cursor=cxn.cursor()??? ? while True:? ? ? ? try:? ? ? ? ? ? l=[ ]??? ? ? ? ? ? studentid =int(input("Please enter your student_id"))??? ? ? ? ? ? a = 'select * from student_info where Student_ID = %studentid'??? ? ? ? ? ? cursor.execute(a)? ??? ? ? ? ? ? for i in cursor:??? ? ? ? ? ? ? ? l.append(i)? ?? ? ? ? ?except:? ??? ? ? ? ? ? print("Student_id not found try again")MySQL 連接沒有問題,select 語句也沒有問題(即,當我在 python 中獨立運行時,查詢運行是正確的),但 似乎我無法在 SQL 查詢中使用 python 中的變量。另外,如果可能的話,請建議任何其他替代方案!
查看完整描述

2 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

復雜性取決于給定輸入的類型。如果你確定輸入的類型,即是字符串還是數字,你可以直接采用Khan 的 Answer,字符串格式更好。幾個例子:


# Method 1(f-string) - if a number

a = f'select * from student_info where Student_ID = {studentid}'

# if string

a = f"select * from student_info where Student_ID = '{studentid}'"

否則,如果給我們的輸入類型是動態的,即可以是字符串或數字,那么這里有一個適合于此的單行:


a = 'select * from student_info where Student_ID = ' + (studentid if studentid.isnumeric() else "'"+studentid+"'")

僅當沒有給出其他條件時,即僅當串聯不會產生不必要的復雜性時,上述情況才是可能的。您還可以使用 f-string:


a = f'''select * from student_info where Student_ID = {(studentid if studentid.isnumeric() else "'"+studentid+"'")}'''


查看完整回答
反對 回復 2023-08-08
?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

如果studentid是字符串,您的 sql 語句(或a變量)應該類似于:

a =''' select * from student_info where Student_ID = '{studentid}'; '''.format(
   studentid=studentid
)

如果它是整數(或數值),則不需要任何引號{studentid}

a =''' select * from student_info where Student_ID = {studentid}; '''.format(
   studentid=studentid
)


查看完整回答
反對 回復 2023-08-08
  • 2 回答
  • 0 關注
  • 233 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號