3

I am trying to build a simple Address book GUI that has a wx.listbox, that holds all the names in the book, first and last. Once clicked, it will return the information attached to the name from a database file. Right now I have it working by just the last name, I am trying to match first and last names. I am not, really, familiar with the SQLite 3 commands and syntax.

The function is below, this works fine now, but I want to change the query to something like:

select * from AddressBook where Last like names[0] and First like names[1]

Any help would be great!

def onListBox(self, event):
    name  =  event.GetEventObject().GetStringSelection()
    names = name.split(',')###names[0]=Last name, names[1] = first name
    cursor = db.cursor()
    cursor.execute("select * from AddressBook where Last like ?",('%'+names[0]+'%',) )
    result  =  cursor.fetchall()
    return result
13
  • Did you try that query? Commented Apr 4, 2017 at 13:36
  • Did you try just adding that second parameter to the query? Commented Apr 4, 2017 at 13:39
  • yeah, it comes back with a syntax error Commented Apr 4, 2017 at 13:39
  • Are you sure that query should be returning anything? What happens when you run it directly on SQLite? Commented Apr 4, 2017 at 13:40
  • 1
    Please show the code from your attempt at implementing the query with the AND clause, and post the traceback of the syntax error. Commented Apr 4, 2017 at 13:58

1 Answer 1

3

The query from your comment should work.

Here is a small working example:

import sqlite3
conn = sqlite3.connect("test.sql")
cursor = conn.cursor()

cursor.execute("create table address_book (first_name text, last_name text)")
names = [["John", "Smith"], ["Jane", "Smith"]]

for first_name, last_name in names:
    cursor.execute("insert into address_book (first_name, last_name) values (?, ?)", (first_name, last_name))

cursor.execute("select * from address_book where first_name like ? and last_name like ?", ("%" + names[0][0] + "%", "%" + names[0][1] + "%"))
print(cursor.fetchall())

It prints:

[('John', 'Smith')]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.