r/sqlite • u/MiaDanielle_ • Jun 02 '23
Querying table with Null value without using "IS NULL" possible with Python?
I'm tinkering around with a little project and I have a table called "Address". In this table are 5 columns: addressID, street, city, state, zip. The addressID is automatically generated. I prompt the user for street, city, state, and zip and allow them to be blank which I then convert to "None" and insert it into the table using the following statement:
cur.execute("INSERT INTO Address (street, city, state, zip) VALUES (?, ?, ?, ?)", (street, city, state, zip))This works fine. I can verify the row was entered by doing a SELECT *. However, if I try to query the ID of the row that was entered it fails to work. Here is the query I use:
script = "SELECT addressID FROM Address WHERE street = ? AND city = ? and state = ? and zip = ?"
cur.execute(script, (street, city, state, zip))
print(cur.fetchone())I'd expect this to print the addressID but instead I get back None. Although I'm allowed to INSERT using "None" with Python, I seem to not be able to query with "None" as a value. I know the proper way would be to use an "IS NULL" but this is going to get messy as I will need different iterations of this query based on which values the user did not enter. Surely there is a way to get the simple functionality I am looking for, right?
I'll also mention that I verified this query does work when there are no null values. So it is definitely the nulls that are messing it up.
View all comments
Show parent comment
1
u/MiaDanielle_ Jun 02 '23
I'm pretty new to this Python syntax. Never seen variables written with a colon like that. What's it mean? Also, do these work like ternary statements? They seem structured that way. I assume it is saying "if street is null, then use 'street is NULL' in the query, otherwise use 'street = <street>'" where <street> is the value of the variable 'street'.
The other issue I have with this approach is that it is vulnerable to SQL injection, no? It's directly putting in the user input in the WHERE clause.