简体   繁体   中英

Make Advanced Searches in SQLite Data Base

I got and address book with names of people. I use the following code to perform a search in the name column:

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")

The name column has the name and the surname ( like, John Smith) The code above works fine when i don't remember the entire name but just the starting letters. But I want that the results show all the matches, not only at the beginning of the names. So, if I got 3 names (Simonne Welsh, Adam Loyd, John Smith) and a type the letter S it has to give the result of the names Simone Welsh and John Smith. How do I do that?

Do this:

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

(include the wildcard before the match string as well as after).

Also, please consider using ( note: corrected this syntax ):

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

or

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

which will:

  1. Make your code safe from SQL injection attacks.

  2. Correctly handle cases in which the text includes special characters, like a single quote (for instance, name of O'Reilly ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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