Python Interface with MySQL: Database Programming Basics

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

Python provides powerful features for database programming, allowing interaction with databases like MySQL, Oracle, and more. The Python DB API is a widely used module that enables creating, accessing, and manipulating data. An interface acts as a bridge between applications and systems, facilitating interaction. APIs, or Application Programming Interfaces, define methods for communication between software components, analogous to a waiter taking orders in a restaurant. Understanding interfaces and APIs is fundamental for building software systems that interact with databases effectively.

  • Python
  • MySQL
  • Database Programming
  • Interfaces
  • APIs

Uploaded on Jul 22, 2024 | 3 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. CHAPTER - XVI INTERFACE PYTHON WITH MYSQL

  2. REFERENCE: CLASS XII TEXT BOOK SUMITA ARORA

  3. INTRODUCTION

  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.

  7. INTERFACE

  8. INTERFACE What is an Interface? Interface is the way for an application to interact with certain system/application.

  9. INTERFACE For Example:

  10. API - APPLICATION PROGRAMMING INTERFACE

  11. API -APPLICATION PROGRAMMING INTERFACE In computer programming, an application programming interface is a set of subroutine definitions, protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication among various components. communication

  12. API -APPLICATION PROGRAMMING INTERFACE 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.

  13. 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).

  14. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING

  15. 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.

  16. BENEFITS OF PYTHON FOR DATABASE PROGRAMMING Python supports SQL cursors. In 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. many programming languages, the

  17. 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.

  18. PYTHON INTEGRATION WITH MYSQL

  19. PYTHON INTEGRATION WITH MYSQL INTRODUCTION 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.

  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 4. mysqlclient 5. OurSQL 3. MySQLDB

  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 MYSQL CONNECTOR PYTHON What is MYSQL Connector Python? or library available in python to communicate with a MySQL MYSQL Connector Python is module

  26. PYTHON INTEGRATION WITH MYSQL ADVANTAGES OF MYSQL CONNECTOR PYTHON

  27. PYTHON INTEGRATION WITH MYSQL ADVANTAGES OF MYSQL CONNECTOR PYTHON 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 maintained. is Python 3 compatible, actively

  28. 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.

  31. PLATFORM

  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 please mention the version of the module and then try to install again. Refer to the above table to install the correct version. If you are facing any problem while installing, pip python==8.0.11 install mysql-connector-

  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 a cursor.close() and MySQL database connection using connection.close() completes. the Cursor object using after your work 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: Step 2: Step 3: Step 4: Step 5: Step 6 Step 7. Start the Python Import Package Open Connection or Connect to database Create a cursor Execute Query Extract data from the result set Close the connection or clean up the environment.

  48. STEPS TO CONNECT MYSQL DATABASE IN PYTHON USING MySQL Connector Python Step 1: script Start the Python Start the Python IDLE editor to write the Step 2: Package. Import MySQL Connector Python import mysql.connetor as SQLCon import mysql.connector Or

  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 is a connection object Mycon=mysql.connector.connect( host='localhost', database='mysql', user='root', password='')

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#