python - 如何从数据库中获取与特定搜索相关的所有信息
问题描述
我想为我的项目构建一个搜索按钮以获取与特定搜索相关的所有信息,即如果数据库中存在两个相似的名字说“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")
解决方案
您不应该同时调用两者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
推荐阅读
- scala - 结构化火花流左外连接的行为类似于内连接
- javascript - 当用户标记不和谐机器人时,我该如何做到这一点,它会回复一条消息?
- sql - 查询如何根据主键选择列中的最高字母?
- c++ - 从复制赋值重载中通过引用返回
- azure - 天蓝色上的 terraform - 创建具有私有连接的密钥库
- python - QuantLib Python Hull White 模型 - RuntimeError:时间 (20) 已超过最大曲线时间 (19)
- c++ - 字符串到C++中的char数组
- typescript - 用打字稿反应导航getparam
- junit5 - Junit中真正的随机单元测试
- r - 如何在 x 轴上仅显示标签的子集?