Parameterized query in SQLite database to use user inputs data to get records by SELECT with WHERE.



Parameterized query in SQLite database to use user inputs data to get records by SELECT with WHERE.

Parameterized query in SQLite database to use user inputs data to get records by SELECT with WHERE.

https://www.plus2net.com/python/sqlite-select.php
About mounting google drive to colab with SQLite database
https://www.plus2net.com/python/sqlite-colab.php
List of all Python SQLite tutorials
https://www.plus2net.com/python/python-sqlite-video.php

It is not safe to use variables directly inside our query when it is coming from unknown sources. While using user input data to build query, we have to ensure that injection attack is not happening. For this reason we have to use parameterized query or prepared statements to run our queries.
Variables are passed by using placeholder ( ? ) separately while sending query and database will execute the query by understanding the role of variables.
From our student table we will collect records of students of class Four by using this parameterized query
my_data=(‘Four’,)
q=”SELECT id, name, class, mark, sex FROM student WHERE class=?”
my_cursor=my_conn.execute(q,my_data)
data_row=my_cursor.fetchall()
for row in data_row:
print(row)

We can use more than one parameter also but note that the sequence of parameters matters here.
my_data=(‘Four’,’Three’)
q=”SELECT id, name, class, mark, sex FROM student WHERE class=? OR class=?”
my_cursor=my_conn.execute(q,my_data)
data_row=my_cursor.fetchall()
for row in data_row:
print(row)

We can use integer as parameter also
my_data=(8)
q=”SELECT id, name, class, mark, sex FROM student WHERE id=?”
my_cursor=my_conn.execute(q,my_data)
data_row=my_cursor.fetchall()
for row in data_row:
print(row)