Notes-Ch-10-Interface Python With Mysql
Notes-Ch-10-Interface Python With Mysql
6. The result set refers to a logical set of records that are fetched from the database by
executing an SQL query and made available to the application program.
>> For Step(vi) Once the result of the query is available in the form of a resultset stored
in a cursor object, we can extract data from the resultset using any of the following
fetch…..() function.
7. The fetchall() method will return all the rows from the resultset in the form of a tuple
containg the records.
>>For Step(vi)#database connected established and cursor object created
Data=cursor.fetchall()
Count=cursor.rowcount()
Print(“Total number of rows retrieved in resultset:”,count)
For row in data:
Print(data)
8. The cursor.rowcount returns how many rows have been so far retrieved through
fetch…() method from the cursor.
9. The fetchmany() method will return only <n> number of rows from the resultset in the
form of a tuple containing records.
>>For Step(vi) data=cursor.fetchmany(4)
10. The fetchone() method will return only one row from the resultset in the form of a tuple
containing a record.
>>For Step(vi) data=cursor.fetchone()
11. After all the processing, the final step need to close the connection established.
>> For Step(vii) the command is as follows:
Mycon.close()
12. Parameterised Queries: We have discussed to execute a simple queries after
establishment of connection to MySql database. Sometimes we need queries which are
based on some parameters or values from outside.
Ex: a=50 select * from student where marks>a;
13. The following are the methods used for parameterized queries:
(i) Old Style: String Templates with % formatting- In this style , string formatting
uses this general form: f%v 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, 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.
Ex: “select * from student where marks>%s” s is a parameter here
The above query is incomplete string(only f, no %v)
e.g, if we want to provide value 50 for %s placeholder in above query string, we
can form the value tuple as follows:
code is:
“Select * from student where marks>%s” %(50)
Now, you can store this query string in variable and then execute that variable
through cursor.execute() method as follows:
St=”select * from student where where marks>%s” %(50,)
Cursor.execute(st)
Data=cursor.fetchall()
For row in data:
Print(row)
(ii) New Style: String Templates with % formatting: The new style of creating SQL
query strings involves the use of the .format() method of the str type.
St=”select * from student where marks>{} and section=’{}’”.format(70,’B’)
Note: The above query string st stores the records return from select * from
student where marks>70 and section=’B’