为了账号安全,请及时绑定邮箱和手机立即绑定

在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 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信