Notes-Ch-10-Interface Python with Mysql

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

DELHI PUBLIC SCHOOL, VIDYUT NAGAR

Class: XII Sub: Informatics Practices


Chapter-10 : Interface Python With MySql

1. How we connect to a MySql Database from within a Python script.


2. In order to connect to a database from within Python we need library that provides
connectivity functionality. There are many different libraries are available for this.
Among these libraries MySql connector is one of the important library to accomplish
this.
3. Steps to connect to MySql from Python:
(i) Start Python
(ii) Import the required package for database programming
(iii) Open a connection to a database
(iv) Create a cursor instance
(v) Execute a query
(vi) Extract a data from result set
(vii) Clean up the environment

>> For Step (i) open Pyhon software


>> For Step (ii) Import mysql.connector Package. For this write command show below:
Import mysql.connector or import mysql.connector as sqltor (sqltor is any
indentifier/variable name)
>> For Step (iii) The connect() function of mysql.connector establishes connection to a
MySql database and requires four parameter which are as follows:
Ex:
Import mysql.connector as sqltor
Mycon=sqltor.connect(host=”localhost”, user=”root”, password=”dpsvn”,
database=”Exam”)
Note: Do not change host and user and its value. The password is the password of your
MySql software that you have given at the time of installation. The database name
Exam is the name of database that you have created and wants to connect with Python.
When database will be connected its all the tables will be able to accept all sql
statements like select, insert,update and delete.
>> If Python reports no error, it means you have successfully connected to mysql
database. You can also checked it by using is_connected() with connected object.
Write this entire command to check:
Import mysql.connector as sqltor
Mycon=sqltor.connect(host=”localhost”, user=”root”, password=”dpsvn”,
database=”Exam”)
If Mycon.is_connected():
Print(“Connection Established Successfully with database”)
//take care of indent of if and print statement
4. A database connection object controls the connection to the database. It represents a
unique session with a database connected from within a program.
5. A database Cursor is a special control structure that facilitates the row by row
processing of records in the resultset, i.e. the set of records retrieved as per query.
>> For Step(iv) You can create an instances of cursor by using cursor() function by
using as follows:
Cursor=Mycon.cursor()
>>For Step(v) When cursor have created, we can execute SQL query by using
execute() function with cursor object as follows:
Cursor.execute(“select * from student”)
Note: As you aware that student is the name of table of Exam data. If you remember
there is a relation between database and table as well as field name and table then you
never do mistakes, otherwise error will be shown.

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)

See the output from the table

(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’

You might also like