繁体   English   中英

在SQLite数据库中进行高级搜索

[英]Make Advanced Searches in SQLite Data Base

我得到了一个带有人名的地址簿。 我使用以下代码在名称列中执行搜索:

register = []
text = "{0}%" .format(self.lineEdit_6.text())
c.execute("select id, name from contacts where nome like '{0}'" .format(text))
for row in c:
    register.append(row)
    self.listWidget_4.addItem(str(row[1]))
    self.listWidget_6.addItem(str(row[0]))
if register == []:
    self.listWidget_4.addItem("No result")

名称列包含名称和姓氏(例如John Smith),当我不记得全名而只记得起始字母时,以上代码可以正常工作。 但我希望结果显示所有匹配项,而不仅仅是名称的开头。 因此,如果我得到3个名字(Simonne Welsh,Adam Loyd,John Smith)和一个字母S,则必须给出名字Simone Welsh和John Smith的结果。 我怎么做?

做这个:

    text = "%{0}%" .format(self.lineEdit_6.text())
    c.execute("select id, name from contacts where nome like '{0}'" .format(text))

(在匹配字符串之前和之后都包含通配符)。

另外,请考虑使用( 注意:此语法已更正 ):

    c.execute("select id, name from contacts where nome like ?", [text])

要么

    c.execute("select id, name from contacts where nome like ?", (text, ))

这将:

  1. 使您的代码免受SQL注入攻击。

  2. 正确处理text包含特殊字符的情况,例如单引号(例如O'Reilly名称)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM