Interface With Python 2
Interface With Python 2
WITH MYSQL
1
Introduction
■ When you design real life applications, you are
bound to encounter situations wherein you
need to manipulate data stored in a database
through an application designed by you.
■ In order to connect to a database from within
the Python, you need a library that provides
connectivity functionality. There are so many
libraries , but we will use mysql connector
library.
2
■ Write the following command:
pip install mysql-connector
in the cmd prompt
■ After installing , open Python shell and write
import mysql.connector
■ If it will not show any error, it means you have
successfully installed it.
3
Open a connection to a database
Execute a query
Member Aliasing
5
con=mysql.connector.connect(host=<HostName>,
user=<username>,
password=<password>,
database=<DatabaseName>)
con=mysql.connector.connect(host=‘localhost’,
user=‘root’,
password=‘123’,
database=‘school’)
6
To check the current user and host of a
system, type the following command:
mysql>select current_user();
7
■ A database cursor is a special control
structure that facilitates the row by
row processing of records in the
resultset, i.e. set of records retrieved
as per query.
9
Return all the records retrieved as
per query in a tuple form.
It will return one record from the
resultset as a tuple. First time, it will fetch the first record,
next time it will fetch the second record.
This method fetches n records
in the form of a tuple.
This property of a cursor object
returns the number of rows retrieved.
10
■ (i) Old Style: String Templates with % formatting
f%v
Where,
f is a template string
v specifies the values to be formatted using the
template. v must be a tuple.
“Select * from student where marks > %s” % (70,)
11
(ii) New Style : String Template with % formatting
12
■ Commit ( ) function is used to save the changes in a
database physically.
■ After performing : insert , update and delete queries ,
call the commit ( ) function with the help of an
connection object.
13
Performing insert operation…..
14