Skip to content
Advertisement

PYTHON SQLITE selecting multiple where conditions that may or may not exist

Working on some code that uses pysimplegui as the UI and SQlite for the data sorting. I’m using SQLite’s execute function to select data based on input from the user in the UI through variables. For example user wants to search for part name they input all or part of the name into the box, hit the search button which then runs my “parts_search” method, which will then only filter the result based on part name. OR the user enters information in multiple boxes which then filters based on the boxes that have information.

This here is runnable code provided you add a file base1.db in the same folder location as the script itself

THE PROBLEM: The commented code at the bottom is where I’m having trouble figuring out (in the “part_search” method). I don’t use all of the variables all the time. Only filter with the variables provided by the user. which means the tuple should only have the variables which was input by the user.

If all the variables were used this is what it would look like. c.execute(filter, (part_name, part_series, part_number, part_size, fit, weld, assemble)) but more often than not only some of those variable will have been used and may need to look like this instead. c.execute(filter, (part_name, part_series, weld)) Somehow I need the variables here to be removeable(for lack of better word)

I’ve been learning a lot about SQLite but I could be seeing tunnel vision and can’t think of a different way to go about this.

Advertisement

Answer

Probably the easiest way to deal with this is to put all the filter conditions and values into lists, and then only add a WHERE clause if the length of the filters list is non-zero. For example:

Note: should your filters ever include OR conditions, you need to parenthesise them when building the query to ensure correct operation i.e.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement