Python如果mysql行不等于输入

问题描述

我的脚本使用 MysqL.connector 模块。

这是我尝试检查的脚本: 我的数据库结构: 名称、类型、前置、块

class database():
    def __init__(self):
        self.Database = MysqL.connect(
            host='localhost',user='root',password='',auth_plugin='MysqL_native_password'
        )
        self.cursor = self.Database.cursor()

    def GetProfileinformations(self,name):
        args = name.split(' ')
        found =  self.cursor.execute('SELECT * FROM list.raids WHERE name=' + args[0])
        sql =  self.cursor.execute('SELECT * FROM list.raids')
        rc = self.cursor.fetchall(sql)
        f = self.cursor.fetchall(found)
        # Check is imput equal to name 
        for _ in f:
            if not found:
                return
        for row in rc:
            try:
                if row[0] == args[0]:
                    if row[3] == 1:
                        if row[2] == 1:
                            print(f"Name {row[0]} found with 1")
                        else:
                            print(f"Name: {row[0]} found with 0")
                    else:
                        print(f"Name: {row[0]} found but is blocked")
            except:
                print("any error")
        self.cursor.close()

现在我的问题是为什么不使用 if existing 函数

            if not found:
                return

祝你有美好的一天,感谢你帮助我

解决方法

您可以使用此游标属性来检查您的查询是否有结果:

if not found.with_rows:
   print("No records found")

您也可以使用:

if found.rowcount <= 0:
    print("No records found")
,

我已经自己解决了:

import mysql.connector as mysql

class database():
    def __init__(self):
        self.Database = mysql.connect(
            host='localhost',user='root',password='',auth_plugin='mysql_native_password'
        )
        self.cursor = self.Database.cursor(buffered=True)

    def IsInSQL(self,name):
        self.cursor.execute(f'SELECT EXISTS(SELECT name AS name FROM list.raids WHERE name = "{name}")')
        f = self.cursor.fetchall()
        if not f:
            return True
        else:
            return False

    def GetProfileInformations(self,name):
        args = name.split(' ')
        self.cursor.execute('SELECT * FROM list.raids')
        rc = self.cursor.fetchall()
        if not self.IsInSQL(args[0]):
            print("nicht gefunden")
        for row in rc:
            try:
                if row[0] == args[0]:
                    if row[3] == 1:
                        if row[2] == 1:
                            print("")
                        else:
                            print("")
                    else:
                        print("not found")

            except:
                print("lel")
        self.cursor.close()