首页 > 解决方案 > 如何从数据库中获取与特定搜索相关的所有信息

问题描述

我想为我的项目构建一个搜索按钮以获取与特定搜索相关的所有信息,即如果数据库中存在两个相似的名字说“Purba”(sqlite3),那么在单击搜索按钮后,两个用户的详细信息应在单独的行中显示在列表框中。

如果搜索到的数据不存在于数据库中,我的代码将显示警告消息,但它仅显示数据库中有关一个用户的信息(例如具有名字“purba”和姓氏“paik”),即使另一个用户(例如有名字“purba”和姓氏“das”)存在于数据库中。如果数据库中不存在搜索的数据,我希望我的代码显示与特定搜索相关的所有用户的信息以及警告消息。

以下是从数据库中获取数据的代码:

 def search(self,EmpID="",Firstname="",Lastname="",DOB="",Age="",Gender="",Address="",Marital_Status="",Email="",Mobile=""):
        print("Database:search method called",EmpID)
        con=sqlite3.connect("Employee.db")
        cur=con.cursor()
        cur.execute("select * from employee where EmpID=? or Firstname=? or Lastname=? or DOB=? or Age=? 
          or Gender=? \
                        or Address=? or Marital_Status=? or Email=? or Mobile=?",(EmpID,Firstname,Lastname,DOB,Age,Gender,Address,Marital_Status,Email,Mobile))
        if(cur.fetchone()) is not None:
            row=cur.fetchall()
            con.close()
            print(EmpID,"Database:search method finished\n")
            return row
        else:
            tkinter.messagebox.showwarning("EMPLOYEE MANAGEMENT SYSTEM","doesn't exist") 

以下是执行列表框中信息的代码:

def SearchDatabase():
            print("employee:search method called")
            for row in p.search(EmpId.get(),firstname.get(),lastname.get(),dob.get(),age.get(),\
                                gender.get(),address.get(),marsta.get(),email.get(),mobile.get()):
                    Emplist.insert(END,row,str(""))
            print("employee:search method finished\n")

标签: pythonsqlitetkinterpython-3.7

解决方案


您不应该同时调用两者fetchone(),并且fetchall()fetchone()从结果集中弹出一条记录。然后fetchall()将获取不包括第一条记录的其余部分。

只需调用fetchall()就足够了:

def search(self,EmpID="",Firstname="",Lastname="",DOB="",Age="",Gender="",Address="",Marital_Status="",Email="",Mobile=""):
  print("Database:search method called",EmpID)
  con=sqlite3.connect("Employee.db")
  cur=con.cursor()
  cur.execute("""select * from employee \
                 where EmpID=? or Firstname=? or Lastname=? or DOB=? or Age=? \
                    or Gender=? or Address=? or Marital_Status=? or Email=? or Mobile=?""",
                 (EmpID,Firstname,Lastname,DOB,Age,Gender,Address,Marital_Status,Email,Mobile))
  row = cur.fetchall()
  if len(row) > 0:
      print('found')
  else:
      messagebox.showwarning("EMPLOYEE MANAGEMENT SYSTEM","doesn't exist")
  con.close()
  print(EmpID,"Database:search method finished")
  return row

推荐阅读