在Python中的mysql.execute语句内使用变量对象

问题描述

我的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中的变量。另外,请提出建议 如果可能的话,还有其他选择!

干杯, 阿迪斯提安

P.S:-这不是我的作业不是。在学习MysqL的过程中,我观看了YouTube,在编码过程中,我想到了做一个简单的python项目。那是我遇到这个错误的时候

解决方法

如果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
)
,

复杂度取决于给定输入的类型。如果您确定输入的类型,即输入的是字符串或数字,则可以直接采用 Khan's 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+"'")}'''