SlideShare a Scribd company logo
CHAPTER - XVI
INTERFACE PYTHON WITH MYSQL
REFERENCE:
CLASS XII
TEXT BOOK
SUMITA ARORA
INTRODUCTION
INTRODUCTION
Every organisation depends on
large databases. These are essentially
collections of tables, and’ connected with
each other through columns. These database
systems support SQL, the Structured Query
Language, which is used to create, access and
manipulate the data.
INTRODUCTION
The Python programming language has
powerful features for database programming.
Python supports various databases like
MySQL, Oracle, Sybase, PostgreSQL, etc.
Python also supports Data Definition
Language (DDL), Data Manipulation Language
(DML) and Data Query Statements.
INTRODUCTION
For database programming, the Python DB
API is a widely used module that provides a
database application programming interface.
INTERFACE
INTERFACE
What is an Interface?
Interface is the way for an application to
interact with certain system/application.
For
Example:
INTERFACE
API - APPLICATION PROGRAMMING INTERFACE
API -APPLICATION PROGRAMMING INTERFACE
In computer programming, an
application programming interface is a set of
subroutine definitions, communication
protocols, and tools for building software. In
general terms, it is a set of clearly defined
methods of communication among various
components.
Consider an API as a waiter in a
restaurant. Suppose you have a menu of your
favourite food and the kitchen is the system
where your order is made. But how do you
take your order till the kitchen? Correct, you
call a waiter, give him/her the order, which in
turns takes your order till the kitchen and
then your order is made there and then
finally, the waiter comes back with your
delicious ordered food.
API -APPLICATION PROGRAMMING INTERFACE
Thus, the API is very much similar to the
waiter. API is the messenger that takes your
order(waiter) and tells the system(kitchen)
what to do (to prepare food) and in return
gives back the response you asked for (waiter
returns with the ordered food).
API -APPLICATION PROGRAMMING INTERFACE
BENEFITS OF PYTHON FOR DATABASE
PROGRAMMING
There are many good reasons to use Python for
programming database applications:
Programming in Python is arguably more
efficient and faster compared to other
languages.
Python is famous for its portability.
It is platform independent.
BENEFITS OF PYTHON FOR DATABASE
PROGRAMMING
Python supports SQL cursors.
In many programming languages, the
application developer needs to take care of the
open and closed connections of the database, to
avoid further exceptions and errors. In Python,
these connections are taken care of.
BENEFITS OF PYTHON FOR DATABASE
PROGRAMMING
Python supports relational database systems.
Python database APIs are compatible with
various databases, so it is very easy to migrate
and port database application interfaces.
BENEFITS OF PYTHON FOR DATABASE
PROGRAMMING
PYTHON INTEGRATION WITH MYSQL
PYTHON INTEGRATION WITH MYSQL
We discuss how to develop and integrate
Python applications that work with a MySQL
database server. Python is dynamic, and
enterprise language and it has all the support
to build large and complex enterprise
applications. MySQL is the world’s most
powerful and used open-source database
provided by Oracle.
INTRODUCTION
PYTHON INTEGRATION WITH MYSQL
PYTHON MODULE FOR COMMUNICATING WITH MYSQL
PYTHON INTEGRATION WITH MYSQL
Total 5 modules available in python to
communicate with a MySQL and provides
MySQL database support to our applications
and they are:-
1. MySQL Connector Python
2. PyMySQL
3. MySQLDB
4. mysqlclient
5. OurSQL
PYTHON INTEGRATION WITH MYSQL
Note: Above all interfaces or modules are
adhere to Python Database API Specification
v2.0 (PEP 249) that means the syntax, method
and the way of access database is the same in
all.
PEP 249 has been designed to encourage
and maintain similarity between the Python
modules that are used to access databases. By
doing this, above all modules are following
rules defined in Python Database API
Specification v2.0 (PEP 249).
PYTHON INTEGRATION WITH MYSQL
You can choose any of the above modules
as per your requirement. The way of accessing
the MySQL database remains the same. We
discuss
MySQL Connector Python
Throughout this chapter.
PYTHON INTEGRATION WITH MYSQL
MYSQL CONNECTOR PYTHON
PYTHON INTEGRATION WITH MYSQL
What is MYSQL Connector Python?
MYSQL Connector Python is module
or library available in python to
communicate with a MySQL
MYSQL CONNECTOR PYTHON
PYTHON INTEGRATION WITH MYSQL
ADVANTAGES OF MYSQL CONNECTOR PYTHON
PYTHON INTEGRATION WITH MYSQL
 MySQL Connector Python is written in pure
Python, and it is self-sufficient to execute
database queries through python.
It is an official Oracle-supported driver to
work with MySQL and python.
It is Python 3 compatible, actively
maintained.
ADVANTAGES OF MYSQL CONNECTOR PYTHON
MYSQL CONNECTOR PYTHON
INSTALLATION : MYSQL CONNECTOR PYTHON
PREREQUISITES
You need root or administrator privileges to perform
the installation process.
Python must installed on your machine.
Note: – MySQL Connector Python requires python to be
in the system’s PATH. Installation fails if it doesn’t find
Python.
On Unix and Unix-like systems, Python generally
located in a directory included in the default PATH
setting.
On Windows, If Python doesn’t exist in the system’s
PATH, please manually add the directory containing
python.exe yourself.
PLATFORM
PLATFORM
Platform(s): 64-bit Windows, Windows 10, Windows
7, Windows 8, Windows Vista, Windows XP, Linux,
Ubuntu Linux, Debian Linux, SUSE Linux, Red Hat Linux,
Fedora, MacOs.
Python version(s): Python 2 and 3 and above.
MySQL Version(s): Greater than 4.1
WAYS TO INSTALL MySQL Connector Python
WAYS TO INSTALL MySQL Connector Python
There are multiple ways to install Oracle’s
MySQL Connector Python on your machine.
Following are the few ways.
Install MySQL Connector Python using the pip
command.
Install MySQL connector python via source
code (via ZIP or TAR file)
WAYS TO INSTALL MySQL Connector Python
Use Built Distribution A package created in
the native packaging format intended for a
given platform. Example, RPM packages for
Linux or MSI installer for windows.
PIP Command to install MySQL Connector
Python
PIP Command to install MySQL Connector
Python
pip install mysql-connector-python
If you are facing any problem while installing,
please mention the version of the module and then try
to install again. Refer to the above table to install the
correct version.
pip install mysql-connector-
python==8.0.11
PYTHON MySQL DATABASE CONNECTION
PYTHON MySQL DATABASE CONNECTION
Goals - In this session, you’ll learn:
How to connect MySQL Server and create a
table in MySQL from Python.
Different MySQL Connection arguments we
can use to connect to MySQL.
How to change the MySQL connection
timeout when connecting through Python.
ARGUMENTS REQUIRED TO CONNECT MYSQL
FROM PYTHON
ARGUMENTS REQUIRED TO CONNECT MYSQL
FROM PYTHON
You need to know the following detail of the
MySQL server to perform the connection from
Python.
Username – i.e., the username that you use
to work with MySQL Server. The default
username for the MySQL database is a root
Password – Password is given by the user at
the time of installing the mysql database. If you
are using root then you won’t need the
password.
ARGUMENTS REQUIRED TO CONNECT MYSQL
FROM PYTHON
Host Name – is the server name or Ip address
on which MySQL is running. if you are running
on localhost, then you can use localhost, or it’s
IP, i.e. 127.0.0.0
Database Name – Database name to which
you want to connect.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Install MySQL Connector Python using pip.
Use the mysql.connector.connect() method
of MySQL Connector Python with required
parameters to connect MySQL.
Use the connection object returned by
a connect() method to create a cursor object to
perform Database Operations.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
The cursor.execute() to execute SQL queries
from Python.
Close the Cursor object using
a cursor.close() and MySQL database connection
using connection.close() after your work
completes.
Catch Exception if any that may occur during
this process.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Follow the steps:-
Step 1: Start the Python
Step 2: Import Package
Step 3: Open Connection or Connect to
database
Step 4: Create a cursor
Step 5: Execute Query
Step 6 Extract data from the result set
Step 7. Close the connection or clean up the
environment.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 1: Start the Python
Start the Python IDLE editor to write the
script
Step 2: Import MySQL Connector Python
Package.
import mysql.connector
Or
import mysql.connetor as SQLCon
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 3: Open Connection or Connect to
database.
Mycon=mysql.connector.connect(
host='localhost',
database='mysql',
user='root',
password='')
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 3: Open Connection or Connect to
database.
Mycon=mysql.connector.connect(
host='localhost',
database='mysql',
user='root',
password='')
Mycon is a connection object
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
What is Database Connection Object?
A Database connection object controls the
connection to the database. It represents a
unique session with a database connected from
within a script or program
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
One can check the connection by writing
the following code.
If mycon.is_connected():
print(“Successfully Connected”)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
What is cursor?
A database cursor is a special control
structure that facilitates the row by
processing of records in the result set.
What is result set?
Result set refers to the logical set of
records that are fetched from the database
by executing an SQL query. It is the set of
records retrieved as per the query.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 4: Create a cursor.
Cursor object=
connectionobject.cursor()
For example:
EmpCursor = mycon.cursor()
Mycon is a connection object
Cursor Object
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 5: Execute Query
EmpCursor.execute(“select * from
emp”)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 6: Extract data from the result set.
After retrieving the records from the
DB using SQL Select Query. You need to extract
records from the result set.
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
You can extract the result set using any of
the following fetch functions/ cursor methods.
.fetchone() .fetchall()
.fetchmany(n)
.close()
Cursor other methods are: -
.callproc() .nextset()
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
.fetchone()
1
Fetch the next row of a query result set,
returning a single sequence, or None when no
more data is available
Data=EmpCursor.fetchone()
V_count=EmpCursor.rowcount
print(“Total Rows retrieved : “,V_count)
print(data)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
.fetchmany(n)
2
Fetch many(n) method will return only the
n number of rows from the result set in the
form of tuple containing the records.
Data=empcursor.fetchmany(4)
V_count=EmpCursor.rowcount
print(“Total Rows retrieved : “,V_count)
for row in data:
print(row)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
.fetchall()
3
Fetch all method will return all the rows
from the result set in the form of tuple
containing the records.
Data=EmpCursor.fetchall()
V_count=EmpCursor.rowcount
print(“Total Rows retrieved : “,V_count)
for row in data:
print(row)
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Step 7. Close the connection or clean up the
environment.
Syntax:
Connectionobject.close()
Example:
Mycon.close()
STEPS TO CONNECT MYSQL DATABASE IN
PYTHON USING MySQL Connector Python
Python Program to Create Table
import mysql.connector as mysql
db = mysql.connect( host = "localhost", user =
"root", passwd = "dbms", database =
“Employee2019" )
cursor = db.cursor()
cursor.execute("CREATE TABLE users (name
VARCHAR(255), user_name VARCHAR(255))")
CREATING TABLE - PYTHON PROGRAM
Python Program to Create Table
import mysql.connector as mysql
db = mysql.connect( host = "localhost", user =
"root", passwd = "dbms", database =
“Emp2019" )
cursor = db.cursor()
cursor.execute("CREATE TABLE users (name
VARCHAR(255), user_name VARCHAR(255))")
CREATING TABLE - PYTHON PROGRAM
SHOW ALL TABLES - PYTHON PROGRAM
Python Program to show all tables.
import mysql.connector as mysql
db = mysql.connect( host = "localhost", user =
"root", passwd = "", database = “Emp2019" )
cursor = db.cursor()
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
for table in tables:
print(table)
SHOW ALL TABLES - PYTHON PROGRAM
PARAMETERISED QUERIES
PARAMETERISED QUERIES
You can run the queries with parameters
For example:
V_marks=56
Select * from student where marks>v_marks
These kind of queries are called as
parameterised queries.
PARAMETERISED QUERIES
FORMING QUERY STRINGS
To form a parameterised queries there are
two methods.
FORMING QUERY STRINGS
1. % formatting – (OLD STYLE)
2. .format() – (NEW STYLE )
FORMING QUERY STRINGS
1. % formatting – (OLD STYLE)
S= “Select * from emp where empid=%s
and dept=‘%s’ “ % ( 1006 , ‘Biotech’)
Example 2: Another Method to use %s :-
Ram=8
Id=2
Input=(ram,id)
Qry= “Update comp set ram=%s where id=%s”
Cursor.execute(Qry,input)
FORMING QUERY STRINGS
1. % formatting – (OLD STYLE)
The string formatting uses the following
style:
f % v
Where f is the string template and
v is the value.
For example:
S=“SELECT * FROM STUDENT WHERE
MARKS>%s” %(70,) v
FORMING QUERY STRINGS
2. .format() – (NEW STYLE )
New style of creating SQL Query stringss
involves the use of .format() method of the str
type.
“We have {0} hectares planted to {1}”
.format(49,”Okra”)
Resultant string will be:
“We have 49 hectares planted to okra”
Contd…
FORMING QUERY STRINGS
2. .format() – (NEW STYLE )
SQL_St=“Select * from student where
makrs>{} and section=‘{}’ “ .format(70,’B’)
After execution SQL_St variable stores:-
“Select * from student where marks >70 and
section=‘B’
INSERT AND UPDATE QUERIES
INSERT AND UPDATE QUERIES
INSERT QUERY
INSERT AND UPDATE QUERIES
INSERT QUERY
To Insert a record in a table use cursor
object. When you perform insert or update
remember to commit the transaction.
MyQuery=“Insert into student ( rollno,name,
marks) values ({},’{}’,{} ) “
.format(1203,’Raman’,67.6)
Cursor.execute(MyQuery)
Mycon.execute()
INSERT AND UPDATE QUERIES
UPDATE QUERY
INSERT AND UPDATE QUERIES
To Update a record in a table use cursor
object. When you perform insert or update
remember to commit the transaction.
MyQuery=“update student set marks={}“ where
marks={}” .format(84,66)
Cursor.execute(MyQuery)
Mycon.execute()
UPDATE QUERY
ThankYou

More Related Content

DOC
Đồ án tốt nghiệp Xây dựng ứng dụng fastfood trên nền android
DOC
Nước ép quả đục
DOCX
Tiểu luận kinh tế vi mô cung cầu lúa gạo và chính sách gái của chính phủ
DOCX
PHÂN TÍCH MÔI TRƯỜNG KINH DOANH CỦA CÔNG TY GAS PETROLIMEX
PDF
Luận văn: Xây dựng mạng xã hội cho cộng đồng “gia sư - học sinh”
PDF
Luận văn: Lập trình game trên thiết bị di động, HAY
DOCX
Báo cáo phân tích thiết kế đồ án game
PDF
Bài 1 Tổng quan về MS Access - Giáo trình FPT
Đồ án tốt nghiệp Xây dựng ứng dụng fastfood trên nền android
Nước ép quả đục
Tiểu luận kinh tế vi mô cung cầu lúa gạo và chính sách gái của chính phủ
PHÂN TÍCH MÔI TRƯỜNG KINH DOANH CỦA CÔNG TY GAS PETROLIMEX
Luận văn: Xây dựng mạng xã hội cho cộng đồng “gia sư - học sinh”
Luận văn: Lập trình game trên thiết bị di động, HAY
Báo cáo phân tích thiết kế đồ án game
Bài 1 Tổng quan về MS Access - Giáo trình FPT

What's hot (20)

DOC
Lập trình microsoft office word với vb.net
DOCX
biến đổi hóa sinh trong bánh mì
PDF
Báo cáo đồ án tôt nghiệp: Xây dựng Website bán hàng thông minh
PDF
Nâng cao chất lượng hàng nông sản xuất khẩu của Việt Nam, HAY
DOCX
Đồ án phát triển sản phẩm thực phẩn khoa công nghệ thực phẩm
DOC
Luận văn thạc sĩ - Nghiên cứu quy trình sản xuất rượu đặc sản từ nguyên liệu ...
DOC
ẨM-THỰC-BA-MIỀN.doc
PDF
Nghiên cứu, đề xuất quy trình chế biến sữa gạo từ gạo đen hữu cơ
DOCX
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
PPT
Cocomo – constructive cost model
PDF
Nghiên cứu chế biến bia nồng độ cồn thấp quy mô phòng thí nghiệm
PDF
Đề tài: Kiểm thử phần mềm trên thiết bị di động, HAY, 9đ
DOCX
Cơ sở lý luận về lợi nhuận trong doanh nghiệp.docx
PDF
Bài tập cơ bản-nâng cao mảng
PDF
Gt co so mat ma hoc
DOC
luận văn tốt nghiệp Nghiên cứu sản xuất nước quả đục từ ổi ruột hồng.doc
PDF
Phân hệ khách hàng và hợp đồng trong CRM của doanh nghiệp
PDF
ứNg dụng một số phương pháp mô tả nhanh trong phát triển sản phẩm thực phẩm t...
PDF
Khóa luận tốt nghiệp cái say trong thơ nguyễn khuyến
PDF
Quan Ly Thu Vien Slide 20081029
Lập trình microsoft office word với vb.net
biến đổi hóa sinh trong bánh mì
Báo cáo đồ án tôt nghiệp: Xây dựng Website bán hàng thông minh
Nâng cao chất lượng hàng nông sản xuất khẩu của Việt Nam, HAY
Đồ án phát triển sản phẩm thực phẩn khoa công nghệ thực phẩm
Luận văn thạc sĩ - Nghiên cứu quy trình sản xuất rượu đặc sản từ nguyên liệu ...
ẨM-THỰC-BA-MIỀN.doc
Nghiên cứu, đề xuất quy trình chế biến sữa gạo từ gạo đen hữu cơ
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
Cocomo – constructive cost model
Nghiên cứu chế biến bia nồng độ cồn thấp quy mô phòng thí nghiệm
Đề tài: Kiểm thử phần mềm trên thiết bị di động, HAY, 9đ
Cơ sở lý luận về lợi nhuận trong doanh nghiệp.docx
Bài tập cơ bản-nâng cao mảng
Gt co so mat ma hoc
luận văn tốt nghiệp Nghiên cứu sản xuất nước quả đục từ ổi ruột hồng.doc
Phân hệ khách hàng và hợp đồng trong CRM của doanh nghiệp
ứNg dụng một số phương pháp mô tả nhanh trong phát triển sản phẩm thực phẩm t...
Khóa luận tốt nghiệp cái say trong thơ nguyễn khuyến
Quan Ly Thu Vien Slide 20081029
Ad

Similar to Chapter 6 Interface Python with MYSQL.pptx (20)

PPTX
Class 12 CS Ch-16 MySQL PPT.pptx
PPTX
unit-5 SQL 1 creating a databse connection.pptx
PDF
Interface python with sql database.pdf
PDF
Interface python with sql database.pdf--
PDF
Interface python with sql database10.pdf
PPTX
Python Programming Part 8 - MYSQL.pptx
PDF
Python - mySOL
PPTX
TO DO APP USING STREAMLIT PYTHON PROJECT
PPTX
Python - db.pptx
PPTX
Chapter -7.pptx
PDF
Pydbapi
DOC
Online Fitness Gym Documentation
PDF
Python
PDF
Integration Microservices
PDF
Www Kitebird Com Articles Pydbapi Html Toc 1
PPTX
PYTHON MYSQL INTERFACE FOR CLASS XII STUDENTS
PDF
Python Database Connection | Edureka
PPTX
Apponix Python Full stack Training course
PDF
Modulenotfounderror No module named 'mysql' in Python
PDF
Socket programming-in-python
Class 12 CS Ch-16 MySQL PPT.pptx
unit-5 SQL 1 creating a databse connection.pptx
Interface python with sql database.pdf
Interface python with sql database.pdf--
Interface python with sql database10.pdf
Python Programming Part 8 - MYSQL.pptx
Python - mySOL
TO DO APP USING STREAMLIT PYTHON PROJECT
Python - db.pptx
Chapter -7.pptx
Pydbapi
Online Fitness Gym Documentation
Python
Integration Microservices
Www Kitebird Com Articles Pydbapi Html Toc 1
PYTHON MYSQL INTERFACE FOR CLASS XII STUDENTS
Python Database Connection | Edureka
Apponix Python Full stack Training course
Modulenotfounderror No module named 'mysql' in Python
Socket programming-in-python
Ad

Recently uploaded (20)

PPTX
GEN. BIO 1 - CELL TYPES & CELL MODIFICATIONS
PPTX
neck nodes and dissection types and lymph nodes levels
PPTX
Cell Membrane: Structure, Composition & Functions
PDF
bbec55_b34400a7914c42429908233dbd381773.pdf
PPTX
INTRODUCTION TO EVS | Concept of sustainability
PPTX
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
PDF
AlphaEarth Foundations and the Satellite Embedding dataset
PPTX
Classification Systems_TAXONOMY_SCIENCE8.pptx
PDF
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
PPTX
Introduction to Fisheries Biotechnology_Lesson 1.pptx
PDF
Phytochemical Investigation of Miliusa longipes.pdf
PDF
HPLC-PPT.docx high performance liquid chromatography
PPTX
G5Q1W8 PPT SCIENCE.pptx 2025-2026 GRADE 5
PDF
An interstellar mission to test astrophysical black holes
PPTX
TOTAL hIP ARTHROPLASTY Presentation.pptx
PDF
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
PPTX
BIOMOLECULES PPT........................
PPTX
Derivatives of integument scales, beaks, horns,.pptx
PPTX
2. Earth - The Living Planet Module 2ELS
PPTX
Introduction to Cardiovascular system_structure and functions-1
GEN. BIO 1 - CELL TYPES & CELL MODIFICATIONS
neck nodes and dissection types and lymph nodes levels
Cell Membrane: Structure, Composition & Functions
bbec55_b34400a7914c42429908233dbd381773.pdf
INTRODUCTION TO EVS | Concept of sustainability
Protein & Amino Acid Structures Levels of protein structure (primary, seconda...
AlphaEarth Foundations and the Satellite Embedding dataset
Classification Systems_TAXONOMY_SCIENCE8.pptx
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
Introduction to Fisheries Biotechnology_Lesson 1.pptx
Phytochemical Investigation of Miliusa longipes.pdf
HPLC-PPT.docx high performance liquid chromatography
G5Q1W8 PPT SCIENCE.pptx 2025-2026 GRADE 5
An interstellar mission to test astrophysical black holes
TOTAL hIP ARTHROPLASTY Presentation.pptx
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
BIOMOLECULES PPT........................
Derivatives of integument scales, beaks, horns,.pptx
2. Earth - The Living Planet Module 2ELS
Introduction to Cardiovascular system_structure and functions-1

Chapter 6 Interface Python with MYSQL.pptx

  • 1. CHAPTER - XVI INTERFACE PYTHON WITH MYSQL
  • 4. INTRODUCTION Every organisation depends on large databases. These are essentially collections of tables, and’ connected with each other through columns. These database systems support SQL, the Structured Query Language, which is used to create, access and manipulate the data.
  • 5. INTRODUCTION The Python programming language has powerful features for database programming. Python supports various databases like MySQL, Oracle, Sybase, PostgreSQL, etc. Python also supports Data Definition Language (DDL), Data Manipulation Language (DML) and Data Query Statements.
  • 6. INTRODUCTION For database programming, the Python DB API is a widely used module that provides a database application programming interface.
  • 8. INTERFACE What is an Interface? Interface is the way for an application to interact with certain system/application.
  • 10. API - APPLICATION PROGRAMMING INTERFACE
  • 11. API -APPLICATION PROGRAMMING INTERFACE In computer programming, an application programming interface is a set of subroutine definitions, communication protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication among various components.
  • 12. Consider an API as a waiter in a restaurant. Suppose you have a menu of your favourite food and the kitchen is the system where your order is made. But how do you take your order till the kitchen? Correct, you call a waiter, give him/her the order, which in turns takes your order till the kitchen and then your order is made there and then finally, the waiter comes back with your delicious ordered food. API -APPLICATION PROGRAMMING INTERFACE
  • 13. Thus, the API is very much similar to the waiter. API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food) and in return gives back the response you asked for (waiter returns with the ordered food). API -APPLICATION PROGRAMMING INTERFACE
  • 14. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING
  • 15. There are many good reasons to use Python for programming database applications: Programming in Python is arguably more efficient and faster compared to other languages. Python is famous for its portability. It is platform independent. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING
  • 16. Python supports SQL cursors. In many programming languages, the application developer needs to take care of the open and closed connections of the database, to avoid further exceptions and errors. In Python, these connections are taken care of. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING
  • 17. Python supports relational database systems. Python database APIs are compatible with various databases, so it is very easy to migrate and port database application interfaces. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING
  • 19. PYTHON INTEGRATION WITH MYSQL We discuss how to develop and integrate Python applications that work with a MySQL database server. Python is dynamic, and enterprise language and it has all the support to build large and complex enterprise applications. MySQL is the world’s most powerful and used open-source database provided by Oracle. INTRODUCTION
  • 20. PYTHON INTEGRATION WITH MYSQL PYTHON MODULE FOR COMMUNICATING WITH MYSQL
  • 21. PYTHON INTEGRATION WITH MYSQL Total 5 modules available in python to communicate with a MySQL and provides MySQL database support to our applications and they are:- 1. MySQL Connector Python 2. PyMySQL 3. MySQLDB 4. mysqlclient 5. OurSQL
  • 22. PYTHON INTEGRATION WITH MYSQL Note: Above all interfaces or modules are adhere to Python Database API Specification v2.0 (PEP 249) that means the syntax, method and the way of access database is the same in all. PEP 249 has been designed to encourage and maintain similarity between the Python modules that are used to access databases. By doing this, above all modules are following rules defined in Python Database API Specification v2.0 (PEP 249).
  • 23. PYTHON INTEGRATION WITH MYSQL You can choose any of the above modules as per your requirement. The way of accessing the MySQL database remains the same. We discuss MySQL Connector Python Throughout this chapter.
  • 24. PYTHON INTEGRATION WITH MYSQL MYSQL CONNECTOR PYTHON
  • 25. PYTHON INTEGRATION WITH MYSQL What is MYSQL Connector Python? MYSQL Connector Python is module or library available in python to communicate with a MySQL MYSQL CONNECTOR PYTHON
  • 26. PYTHON INTEGRATION WITH MYSQL ADVANTAGES OF MYSQL CONNECTOR PYTHON
  • 27. PYTHON INTEGRATION WITH MYSQL  MySQL Connector Python is written in pure Python, and it is self-sufficient to execute database queries through python. It is an official Oracle-supported driver to work with MySQL and python. It is Python 3 compatible, actively maintained. ADVANTAGES OF MYSQL CONNECTOR PYTHON
  • 29. INSTALLATION : MYSQL CONNECTOR PYTHON
  • 30. PREREQUISITES You need root or administrator privileges to perform the installation process. Python must installed on your machine. Note: – MySQL Connector Python requires python to be in the system’s PATH. Installation fails if it doesn’t find Python. On Unix and Unix-like systems, Python generally located in a directory included in the default PATH setting. On Windows, If Python doesn’t exist in the system’s PATH, please manually add the directory containing python.exe yourself.
  • 32. PLATFORM Platform(s): 64-bit Windows, Windows 10, Windows 7, Windows 8, Windows Vista, Windows XP, Linux, Ubuntu Linux, Debian Linux, SUSE Linux, Red Hat Linux, Fedora, MacOs. Python version(s): Python 2 and 3 and above. MySQL Version(s): Greater than 4.1
  • 33. WAYS TO INSTALL MySQL Connector Python
  • 34. WAYS TO INSTALL MySQL Connector Python There are multiple ways to install Oracle’s MySQL Connector Python on your machine. Following are the few ways. Install MySQL Connector Python using the pip command. Install MySQL connector python via source code (via ZIP or TAR file)
  • 35. WAYS TO INSTALL MySQL Connector Python Use Built Distribution A package created in the native packaging format intended for a given platform. Example, RPM packages for Linux or MSI installer for windows.
  • 36. PIP Command to install MySQL Connector Python
  • 37. PIP Command to install MySQL Connector Python pip install mysql-connector-python If you are facing any problem while installing, please mention the version of the module and then try to install again. Refer to the above table to install the correct version. pip install mysql-connector- python==8.0.11
  • 38. PYTHON MySQL DATABASE CONNECTION
  • 39. PYTHON MySQL DATABASE CONNECTION Goals - In this session, you’ll learn: How to connect MySQL Server and create a table in MySQL from Python. Different MySQL Connection arguments we can use to connect to MySQL. How to change the MySQL connection timeout when connecting through Python.
  • 40. ARGUMENTS REQUIRED TO CONNECT MYSQL FROM PYTHON
  • 41. ARGUMENTS REQUIRED TO CONNECT MYSQL FROM PYTHON You need to know the following detail of the MySQL server to perform the connection from Python. Username – i.e., the username that you use to work with MySQL Server. The default username for the MySQL database is a root Password – Password is given by the user at the time of installing the mysql database. If you are using root then you won’t need the password.
  • 42. ARGUMENTS REQUIRED TO CONNECT MYSQL FROM PYTHON Host Name – is the server name or Ip address on which MySQL is running. if you are running on localhost, then you can use localhost, or it’s IP, i.e. 127.0.0.0 Database Name – Database name to which you want to connect.
  • 43. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python
  • 44. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Install MySQL Connector Python using pip. Use the mysql.connector.connect() method of MySQL Connector Python with required parameters to connect MySQL. Use the connection object returned by a connect() method to create a cursor object to perform Database Operations.
  • 45. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python The cursor.execute() to execute SQL queries from Python. Close the Cursor object using a cursor.close() and MySQL database connection using connection.close() after your work completes. Catch Exception if any that may occur during this process.
  • 46. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python
  • 47. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Follow the steps:- Step 1: Start the Python Step 2: Import Package Step 3: Open Connection or Connect to database Step 4: Create a cursor Step 5: Execute Query Step 6 Extract data from the result set Step 7. Close the connection or clean up the environment.
  • 48. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 1: Start the Python Start the Python IDLE editor to write the script Step 2: Import MySQL Connector Python Package. import mysql.connector Or import mysql.connetor as SQLCon
  • 49. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 3: Open Connection or Connect to database. Mycon=mysql.connector.connect( host='localhost', database='mysql', user='root', password='')
  • 50. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 3: Open Connection or Connect to database. Mycon=mysql.connector.connect( host='localhost', database='mysql', user='root', password='') Mycon is a connection object
  • 51. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python What is Database Connection Object? A Database connection object controls the connection to the database. It represents a unique session with a database connected from within a script or program
  • 52. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python One can check the connection by writing the following code. If mycon.is_connected(): print(“Successfully Connected”)
  • 53. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python What is cursor? A database cursor is a special control structure that facilitates the row by processing of records in the result set. What is result set? Result set refers to the logical set of records that are fetched from the database by executing an SQL query. It is the set of records retrieved as per the query.
  • 54. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 4: Create a cursor. Cursor object= connectionobject.cursor() For example: EmpCursor = mycon.cursor() Mycon is a connection object Cursor Object
  • 55. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 5: Execute Query EmpCursor.execute(“select * from emp”)
  • 56. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 6: Extract data from the result set. After retrieving the records from the DB using SQL Select Query. You need to extract records from the result set.
  • 57. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python You can extract the result set using any of the following fetch functions/ cursor methods. .fetchone() .fetchall() .fetchmany(n) .close() Cursor other methods are: - .callproc() .nextset()
  • 58. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python .fetchone() 1 Fetch the next row of a query result set, returning a single sequence, or None when no more data is available Data=EmpCursor.fetchone() V_count=EmpCursor.rowcount print(“Total Rows retrieved : “,V_count) print(data)
  • 59. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python .fetchmany(n) 2 Fetch many(n) method will return only the n number of rows from the result set in the form of tuple containing the records. Data=empcursor.fetchmany(4) V_count=EmpCursor.rowcount print(“Total Rows retrieved : “,V_count) for row in data: print(row)
  • 60. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python .fetchall() 3 Fetch all method will return all the rows from the result set in the form of tuple containing the records. Data=EmpCursor.fetchall() V_count=EmpCursor.rowcount print(“Total Rows retrieved : “,V_count) for row in data: print(row)
  • 61. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 7. Close the connection or clean up the environment. Syntax: Connectionobject.close() Example: Mycon.close()
  • 62. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Python Program to Create Table import mysql.connector as mysql db = mysql.connect( host = "localhost", user = "root", passwd = "dbms", database = “Employee2019" ) cursor = db.cursor() cursor.execute("CREATE TABLE users (name VARCHAR(255), user_name VARCHAR(255))")
  • 63. CREATING TABLE - PYTHON PROGRAM
  • 64. Python Program to Create Table import mysql.connector as mysql db = mysql.connect( host = "localhost", user = "root", passwd = "dbms", database = “Emp2019" ) cursor = db.cursor() cursor.execute("CREATE TABLE users (name VARCHAR(255), user_name VARCHAR(255))") CREATING TABLE - PYTHON PROGRAM
  • 65. SHOW ALL TABLES - PYTHON PROGRAM
  • 66. Python Program to show all tables. import mysql.connector as mysql db = mysql.connect( host = "localhost", user = "root", passwd = "", database = “Emp2019" ) cursor = db.cursor() cursor.execute("SHOW TABLES") tables = cursor.fetchall() for table in tables: print(table) SHOW ALL TABLES - PYTHON PROGRAM
  • 68. PARAMETERISED QUERIES You can run the queries with parameters For example: V_marks=56 Select * from student where marks>v_marks These kind of queries are called as parameterised queries.
  • 70. To form a parameterised queries there are two methods. FORMING QUERY STRINGS 1. % formatting – (OLD STYLE) 2. .format() – (NEW STYLE )
  • 71. FORMING QUERY STRINGS 1. % formatting – (OLD STYLE) S= “Select * from emp where empid=%s and dept=‘%s’ “ % ( 1006 , ‘Biotech’) Example 2: Another Method to use %s :- Ram=8 Id=2 Input=(ram,id) Qry= “Update comp set ram=%s where id=%s” Cursor.execute(Qry,input)
  • 72. FORMING QUERY STRINGS 1. % formatting – (OLD STYLE) The string formatting uses the following style: f % v Where f is the string template and v is the value. For example: S=“SELECT * FROM STUDENT WHERE MARKS>%s” %(70,) v
  • 73. FORMING QUERY STRINGS 2. .format() – (NEW STYLE ) New style of creating SQL Query stringss involves the use of .format() method of the str type. “We have {0} hectares planted to {1}” .format(49,”Okra”) Resultant string will be: “We have 49 hectares planted to okra” Contd…
  • 74. FORMING QUERY STRINGS 2. .format() – (NEW STYLE ) SQL_St=“Select * from student where makrs>{} and section=‘{}’ “ .format(70,’B’) After execution SQL_St variable stores:- “Select * from student where marks >70 and section=‘B’
  • 75. INSERT AND UPDATE QUERIES
  • 76. INSERT AND UPDATE QUERIES INSERT QUERY
  • 77. INSERT AND UPDATE QUERIES INSERT QUERY To Insert a record in a table use cursor object. When you perform insert or update remember to commit the transaction. MyQuery=“Insert into student ( rollno,name, marks) values ({},’{}’,{} ) “ .format(1203,’Raman’,67.6) Cursor.execute(MyQuery) Mycon.execute()
  • 78. INSERT AND UPDATE QUERIES UPDATE QUERY
  • 79. INSERT AND UPDATE QUERIES To Update a record in a table use cursor object. When you perform insert or update remember to commit the transaction. MyQuery=“update student set marks={}“ where marks={}” .format(84,66) Cursor.execute(MyQuery) Mycon.execute() UPDATE QUERY