【问题标题】:Using variable(objects) inside a mysql.execute() statement in Python在 Python 中的 mysql.execute() 语句中使用变量(对象)
【发布时间】:2021-01-01 18:35:03
【问题描述】:

我的 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 项目。那是我遇到这个错误的时候

【问题讨论】:

  • 请注意,在“l.append(i)”之后的“try”语句中,我们可以使用“print(l)”语句

标签: python mysql python-3.x mysql-connector mysql-connector-python


【解决方案1】:

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

【讨论】:

  • 你能推荐一本书或一个视频,我可以从中进一步了解这种连接性吗???
  • @Python-Freelancer wdym 连接?
【解决方案2】:

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

【讨论】:

  • 如果输入没有正确转义,这很容易受到 SQL 注入的攻击。
  • 是的。这是一个有效的声明。
猜你喜欢
  • 2013-02-26
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
  • 2016-09-21
  • 2020-04-16
  • 2010-10-28
相关资源
最近更新 更多