Interface Python With MYSQL - Tutorial - 2
Interface Python With MYSQL - Tutorial - 2
Tutorial_2
Class – XII – Computer science
Hopefully all of you go through the previous uploaded material and also practiced on your computer system.
So, now you have the idea about interaction between Python and MySQL database.
In our last material we only performing simple query to display all records from a table using the command
like :
Parameterised Queries:-
You may need to run queries in your Python program which are based on some parameters or values that you
provide from outside.
Like:
Such queries are called parameterised queries. To execute parameterised queries in a mysql.connector
connection, you nedd to form SQL query strings that include values of parameters.
Let us talk about how you can form such query strings:
There are two styles you can use any one of them as follows:
Where f is a template string and v specifies the value or values to be formatted using that template. If multiple
values are to be formatted then v must be a tuple. For this you can write the SQL query in a string but use a %s
code in place of the value to be provided as a parameter.
for single value to be stored
For example:
in a tuple, comma use to
“select * from Student where marks > %s” %(75,) follow it
Program Coding Example:
Assume that the Student table is exists in the database Myschool ( which we created in MySQL in our previous
material – all programs shown here based on that table)
Program: to display the students details who scored more than 75.
Output:
OR
If you want to store the above query string in variable and then execute that variable through cursor.execute()
method as shown below:
cursor.execute(mystr)
For example:
mystr = “select * from Student where marks > %s and class = ‘%s’ “ %(75, ‘xi’)
Program Example:
Program: to display the student details who scored more than 75 and belongs to class xi
p = (m, x) # tuple
cursor.execute(mystr, p)
Program Example: To display the student details who scored more than a specified number (given by
user) and belongs to a specified class (given by the user)
Output:
for example:
OR
mystr = “select * from Student where marks > {} and class = ‘{}’ “ .format(75, ‘xi’)
mystr = “select * from Student where marks > {0} and class = ‘{1}’ “ .format(75, ‘xi’)
( Here {0} and {1} are the placeholders; values are substituted from (75, ‘xi) ;
Program example:
OR
Output:
Program example – based on user given values at runtime.
Output:
Another example – we supply the values using named arguments. The arguments may be supplied in
any order.
Program example:
Output:
OR
For example:-
Output: