Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views

Python MySQL Connectivity

Here is the code with the missing statements: import mysql.connector con1=mysql.connector.connect(host="localhost",user="root",password="tiger",database="school") mycursor=con1.cursor() mycursor.execute("select * from student where Marks>75") data=mycursor.fetchall() print(data) con1.close()

Uploaded by

Taniya Swain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Python MySQL Connectivity

Here is the code with the missing statements: import mysql.connector con1=mysql.connector.connect(host="localhost",user="root",password="tiger",database="school") mycursor=con1.cursor() mycursor.execute("select * from student where Marks>75") data=mycursor.fetchall() print(data) con1.close()

Uploaded by

Taniya Swain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

INTERFACE WITH

Learning Objectives

The Participants will be able to :


❑Connect SQL with Python.
❑Create Database connectivity Applications.
❑Perform Insert, Update, Delete queries.
❑Display data by using fetchone(),fetchall(),rowcount.
Knowledge about MySQL Installation
❖MySQL is the most popular Open source Software.

❖ It is available free of cost.

❖ It is written in C and C++.


❖ It supports many operating systems like Windows, Unix, Linux etc. with many
languages like C, C++,JAVA,PHP, Python .
❖ It is quicker than other databases.
❖ it can work well even with the large data set.
To download MySQL visit MySQL official website.

http://www.mysql.com/downloads OR dev.mysql.com/download
Type the name of the site
Connotation of Database Connectivity
❖ Every application require data to be stored for future reference.
Today every application stores data in database for this purpose.

❖ For example, reservation system stores passengers details for reserving


the seats and later on for sending some messages or for printing tickets.

❖In school student details are saved for many reasons like attendance, fee
collections, report cards etc.

❖Python allows us to connect all types of database like Oracle, SQL


Server, MySQL.

❖In this session we will consider Python as the Front end and MySQL as the
Backend learn to setup connection between two.
Connecting MySQL with Python
Python has different APIs available for working with different types of
databases, we need to first download the MYSQL API available for Python
These APIs facilitate Python to work with databases in the Python shell as
follows :

❑ Importing the API Module.


❑ Acquiring a connection with the database.
❑ Issuing database commands in Python.
❑ Closing the connection
Python - MySQL Database access
There are three MySQL APIs for Python that are currently maintained :

▪ mysql-connector-python – This is a library provided by MySQL


Community.

▪ mysqldb – This is a library that connects MySQL from Python. It is


written in C Language .

▪ pymysql – This is a library that connects MySQL from Python. It is a pure


Python library.
INSTALL MySQL CONNECTOR FOR PYTHON USING PIP COMMAND

Note: Please make sure that


you have Python and MySQL
installed in your computer
before starting connectivity and
Internet connection should be
on at the time of executing pip
command.
Creating Database Connectivity Applications
Five major steps for connecting MySQL and Python

Import the package mysql.connector

Create a connection Object

Create a cursor instance

Execute a query

Clean up the environment


Import the package MySQL Connector

To import the MySQL connector package follow the steps :


1. Open the Python IDLE
2. Type import mysql.connector Member
OR Aliasing
import mysql.connector as sq
If no Error occur, it
means MySQL
connector is
working properly
Create a connection Object
The connect() function of mysql.connector package is used to establish a connection
to MySQL database.
Syntax : <Connection-Object>=mysql.connector.connect(host=<hostname>,
user=<username>,passwd=<password>,[database=<database>])
Here,
▪ Host Name : It is the server name or IP address on which your MySQL is running.
▪ User Name : It is given to work with MySQL server, the default username is “root”.
▪ Password : It is given by the user at the time of installation of the MySQL database.
You can write “password” OR “passwd”
▪ Database: It is the database name of a MySQL database. This is an optional
parameter.
Create a Cursor Instance
Next step, is to use the connection object returned by the connect()
method to create a cursor object. You can create a cursor object
using the cursor() method of the connection object. The cursor
object is used to execute statements to perform database operations.
Syntax:-
<cursor-object>= <connection-object>.cursor()
For Example:-
cur=ob.cursor()
Here cur is the cursor object created using connection object ob using
cursor() method.
Execute a Query
Once you have created a cursor, you can execute SQL query using
execute() function with cursor object.
■ Syntax :
cursor-object.execute(<SQL Query string>)
▪ For Example :
cur.execute(“select * from Employee")
Here, cur is a cursor object which uses execute method to run the SQL query
is given in the form of a string.

Note:- You can execute any SQL query with the help execute() method.
Clean up the Environment
Once the processing on MySQL database is over the connection
as well as cursor is closed by using close() method of the
corresponding object.
➢ Close the MySQL database connection using
<Connectionobject>.close()
For Example :
ob.close()
➢ Close the cursor object using a <cursor object> .close()
For Example :
cur.close()
Simple code to connect MySQL and Python
import mysql.connector as sql
db=sql.connect(host="localhost",user="root",passwd="1234",)
if db.is_connected():
print("successfully connected")
else:
print(“Not connected")

Mycur=db.cursor()
Mycur.execute("create database Employee")
print("successfully created the Database")
Mycur.close()
db.close()
Performing MYSQL Queries

Insert, Update and Delete in


MySQL Connector for Python
{Single Row Command}
commit() function
After performing any DML operation such as insert, update
and delete, it is mandatory to commit the DML by executing
commit () from DB connector object. Otherwise the changes
will not get reflected in the data base object(table)
Syntax :
<Connection object>.commit()
Example :
ob.commit()
EXTRACT DATA FROM RESULT SET
Whenever we used to retrieve records from the database using select
command we need the following functions:
❑ fetchone() : This method retrieves the first record of the database in the
form of list/tuple, next time it will fetch the second record. if no more rows
are available it returns None.
Syntax : <identifier>=<cursor identifier>.fetchone()
❑ fetchmany(n) : This Method fetches the next set of rows of a query and
return a list of tuple. The number of rows returned can be specified using
the n argument, which default to one. If no more rows are available it
returns an empty list.
Syntax : <identifier>=<cursor identifier>.fetchmany(n)
❑ fetchall() : It fetches all records from the database and it returns a list of tuple.
Syntax : <identifier>=<cursor identifier>.fetchall()
rowcount
❖ It is not a function, It is the property of a cursor object.
❖ It is used to return the number of rows returned for SELECT statements,
or the number of rows effected by DML statement such as INSERT,
UPDATE, etc.
Syntax :
<identifier>= <cursor object>.rowcount
For Example:
data=cur.rowcount

Note :- rowcount is an attribute


FORMATTING THE QUERY STRING(Parameterized Queries)

Instead of passing value we will first accept value from the user and the value is
passed to the query using Two Methods
1. OLD STYLE ( Templates with % format)
General form: f%v
f – template string
v – value / values to be formatted( v must be a tuple)

Example: “select * from empdata where sal> %s” % (30000, )

2. NEW STYLE ( String Template with { } formatting.


General form: template.format(p0,p1,…./ k0=v0, k1=v1,….)
Example:
“select * from empdata where sal>{ } or Empname=’{ }’ “ .format(1000, ‘Neha’)
Example of Sample code to formatting the query
The code given below reads the following record
from the table named student and displays only
those records who have marksgreater than 75:
RollNo – integer,Name – string,
Clas – integer Marks – integer

Note the following to establish connectivity between Python


and MYSQL:
• Username is root Password is tiger
The table exists in a MYSQL database named school.
Write the following missing statements to
complete the code: Ans:
Statement 1 – to form the cursor object Statement 1:
Statement 2 – to execute the query that extracts con1.cursor()
records of those studentswhose marks are greater Statement 2:
than 75. mycursor.execute("select *
Statement 3- to read the complete result of the query from student
(records whose marks are greater than 75) into the where Marks>75")
object named data, from the table student inthe Statement 3:
mycursor.fetchall()
database.

You might also like