SlideShare a Scribd company logo
INTERF
ACE PYTHON
WITH MYSQL
Connecting Python application with
SQL-Connectivity python for beginners easy explanation with concepts and output .pptx
Introductio
n
 Every application required data to be stored for future
reference to manipulate data. 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 etc.
 In school student details are saved for many reasons
like attendance, fee collections, exams, report card etc.
 Python allows us to connect all types of database like
Oracle, SQLServer, MySQL .
 In our syllabus we have to understand how to connect
Python programs with MySQL
Pre-requisite to connect Python with
MySQL
 Before we connect python program with any database
like MySQL we need to build a bridge to connect
Python and MySQL.
 T
o build this bridge so that data can travel both ways
we need a connector called “mysql.connector”.
 We can install “mysql.connector” by using
following methods:
 At command prompt (Administrator login)
 Type “pip install mysql.connector” and press enter
 (internet connection is required)
 This connector will work only for MySQL 5.7.3 or later
 Or open
“https://dev.mysql.com/downloads/connector/python/”
anddownloadconnectorasper OS and Python version.
Connecting to MySQL from
Python
 Once the connector is installed you are ready to
connect your python program to MySQL.
 The following steps to follow while connecting your
python program with MySQL
 Open python
 Import the package required (import
mysql.connector)
 Open the connection to database
 Create a cursor instance
 Execute the query and store it in resultset
 Extract data from resultset
 Clean up the environment
Importing
mysql.connector
import mysql.connector
Or
import mysql.connector as ms
Here “ms” is an alias, so every time we can use “ms” in
place of “mysql.connector”
Open a connection to MySQL
Database
 T
o create connection, connect( ) function is used
 Its syntax is:
 connect(host=<server_name>,user=<user_name>,
passwd=<password>[,database=<database>])
 Here server_name means database servername, generally
it is given as “localhost”
 User_name means user by which we connect with mysql
generally it is given as “root”
 Password is the password of user “root”
 Database is the name of database whose data(table) we
want to use.
Example: To establish
connection with MySQL
is_connected() function returns
true if connection is established
otherwise false
“mys” is an alias of package
“mysql.connector”
“mycon” is connection object which storesconnection established with MySQL
Table to work
(emp)
Creating
Cursor
 It is a useful control structure of database connectivity.
 When we fire a query to database, it is executed and
resultset (set of records) is sent over the connection in one
go.
 We may want to access data one row at a time, but query
processing cannot happens as one row at a time, so cursor
help usin performing this task.
 Cursor stores all the data as a temporary container of
returned data and we can fetch data one row at a time
from Cursor.
Creating Cursor and Executing
Query
 TO CREATE CURSOR
 We use cursor() function to create a cursor
 Cursor_name = connectionObject.cursor( )
 For e.g.
mycursor = mycon.cursor()
 TO EXECUTE QUERY
 We use execute( ) function to send query to
connection
 Cursor_name.execute(query)
 For e.g.
mycursor.execute(“select * from emp )
‟
Example -
Cursor
Output shows cursor is created and query is fired and stored, but no data is
coming. T
o fetch data we have to use functions like fetchall( ), fetchone( ),
fetchmany( ) are used.
mysql.connector as mys
Mysql connector
mys
SQL-Connectivity python for beginners easy explanation with concepts and output .pptx
Fetchall( ) – method extracts all rows
SQL-Connectivity python for beginners easy explanation with concepts and output .pptx
INSERTING RECORDS
Inserting data in MySQL table
from Python
 INSERT and UPDATE operation are executed in the
same way we execute SELECT query using execute(
) but one thing to remember, after executing DML
Commands -insert or update or delete query we
must commit our query using connection object
with commit( ).
 For e.g. (if our connection object nameis mycon)
mycon.commit( )
Example : inserting
data
BEFORE PROGRAM
EXECUTION
AFTER PROGRAM
EXECUTION
RETRIEVING RECORDS
Fetching(extracting) data from
ResultSet
 T
o extract data from cursor following functions are
used:
 fetchall( ) : it will return all the record in the form of
tuple.
 fetchone( ) : it return one record from the result set. i.e.
first time it will return first record, next time it will return
second record and so on. If no more record it will
return None.
 fetchmany(n) : it will return n number of records. It no
more record it will return an empty tuple.
 rowcount: it will return number of rows retrieved from
the cursor so far.
Example –
fetchall()
Example 2 –
fetchall()
Example 3 –
fetchall()
Example 4:
fetchone()
Example 5:
fetchmany(n)
Guess the
output
SEARCHING RECORDS
Parameterized
Query
 We can pass values to query to perform dynamic
search like we want to search for any employee
number entered during runtime or to search any
other column values.
 T
o Create Parameterized query we can use various
methods like:
 Concatenating dynamic variable to
query values are entered.
 String template with % formatting
 String template with { } and format function
in
which
Concatenating variable with
query
String template with %s
formatting
 In this method we will use %s in place of values to
substitute and then pass the value for that place.
String template with %s
formatting
String template with { }
and format( )
 In this method in place of % s we will use { } and to pass values for
these placeholder format( ) is used. Inside we can optionally give
0,1,2… values for e.g.
 {0},{1} but its not mandatory. we can also optionally pass named
parameter inside { } sothat while passing
we
need to
pass.
not
to
For
e.g.
values through format
function remember the
order of value
{roll},{name} etc.
String template with { }
and format( )
String template with { }
and format()
UPDATING RECORDS
Example: Updating
record
VINOD
KUMAR
VERMA,
PGT(CS),
KV
OEF
KANPUR
&
SACHIN
BHARDWAJ,
PGT(CS),
KV
NO.1
T
E
Z
P
U
R
DELETING RECORDS

More Related Content

PPTX
015. Interface Python with sql interface ppt class 12
PPTX
Interface Python with MySQLwedgvwewefwefwe.pptx
PPTX
Interface Python with MySQL connectivity.pptx
PDF
Interface Python with MySQL.pdf
PPTX
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
PPTX
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PPTX
python db connection samples and program
PPTX
MySql Interface database in sql python my.pptx
015. Interface Python with sql interface ppt class 12
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQL connectivity.pptx
Interface Python with MySQL.pdf
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
python db connection samples and program
MySql Interface database in sql python my.pptx

Similar to SQL-Connectivity python for beginners easy explanation with concepts and output .pptx (20)

PDF
24. SQL .pdf
PPTX
interface with mysql.pptx
PPTX
Interfacing python to mysql (11363255151).pptx
PPTX
Database Connectivity using Python and MySQL
PDF
015. Interface Python with MySQL.pdf
PPTX
PythonDatabaseAPI -Presentation for Database
PPTX
PYTHON MYSQL INTERFACE FOR CLASS XII STUDENTS
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
PPTX
Database connectivity in python
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
Chapter 6 Interface Python with MYSQL.pptx
PPTX
Class 12 CS Ch-16 MySQL PPT.pptx
PDF
Develop Python Applications with MySQL Connector/Python
PDF
Mysql python
24. SQL .pdf
interface with mysql.pptx
Interfacing python to mysql (11363255151).pptx
Database Connectivity using Python and MySQL
015. Interface Python with MySQL.pdf
PythonDatabaseAPI -Presentation for Database
PYTHON MYSQL INTERFACE FOR CLASS XII STUDENTS
Pyhton with Mysql to perform CRUD operations.pptx
Database connectivity in python
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
Chapter 6 Interface Python with MYSQL.pptx
Class 12 CS Ch-16 MySQL PPT.pptx
Develop Python Applications with MySQL Connector/Python
Mysql python
Ad

Recently uploaded (20)

PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Lesson notes of climatology university.
PPTX
Presentation on HIE in infants and its manifestations
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
Complications of Minimal Access Surgery at WLH
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
master seminar digital applications in india
PDF
RMMM.pdf make it easy to upload and study
PDF
Anesthesia in Laparoscopic Surgery in India
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
FourierSeries-QuestionsWithAnswers(Part-A).pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
VCE English Exam - Section C Student Revision Booklet
STATICS OF THE RIGID BODIES Hibbelers.pdf
Final Presentation General Medicine 03-08-2024.pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Lesson notes of climatology university.
Presentation on HIE in infants and its manifestations
O7-L3 Supply Chain Operations - ICLT Program
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Computing-Curriculum for Schools in Ghana
Complications of Minimal Access Surgery at WLH
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
master seminar digital applications in india
RMMM.pdf make it easy to upload and study
Anesthesia in Laparoscopic Surgery in India
Ad

SQL-Connectivity python for beginners easy explanation with concepts and output .pptx

  • 1. INTERF ACE PYTHON WITH MYSQL Connecting Python application with
  • 3. Introductio n  Every application required data to be stored for future reference to manipulate data. 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 etc.  In school student details are saved for many reasons like attendance, fee collections, exams, report card etc.  Python allows us to connect all types of database like Oracle, SQLServer, MySQL .  In our syllabus we have to understand how to connect Python programs with MySQL
  • 4. Pre-requisite to connect Python with MySQL  Before we connect python program with any database like MySQL we need to build a bridge to connect Python and MySQL.  T o build this bridge so that data can travel both ways we need a connector called “mysql.connector”.  We can install “mysql.connector” by using following methods:  At command prompt (Administrator login)  Type “pip install mysql.connector” and press enter  (internet connection is required)  This connector will work only for MySQL 5.7.3 or later  Or open “https://dev.mysql.com/downloads/connector/python/” anddownloadconnectorasper OS and Python version.
  • 5. Connecting to MySQL from Python  Once the connector is installed you are ready to connect your python program to MySQL.  The following steps to follow while connecting your python program with MySQL  Open python  Import the package required (import mysql.connector)  Open the connection to database  Create a cursor instance  Execute the query and store it in resultset  Extract data from resultset  Clean up the environment
  • 6. Importing mysql.connector import mysql.connector Or import mysql.connector as ms Here “ms” is an alias, so every time we can use “ms” in place of “mysql.connector”
  • 7. Open a connection to MySQL Database  T o create connection, connect( ) function is used  Its syntax is:  connect(host=<server_name>,user=<user_name>, passwd=<password>[,database=<database>])  Here server_name means database servername, generally it is given as “localhost”  User_name means user by which we connect with mysql generally it is given as “root”  Password is the password of user “root”  Database is the name of database whose data(table) we want to use.
  • 8. Example: To establish connection with MySQL is_connected() function returns true if connection is established otherwise false “mys” is an alias of package “mysql.connector” “mycon” is connection object which storesconnection established with MySQL
  • 10. Creating Cursor  It is a useful control structure of database connectivity.  When we fire a query to database, it is executed and resultset (set of records) is sent over the connection in one go.  We may want to access data one row at a time, but query processing cannot happens as one row at a time, so cursor help usin performing this task.  Cursor stores all the data as a temporary container of returned data and we can fetch data one row at a time from Cursor.
  • 11. Creating Cursor and Executing Query  TO CREATE CURSOR  We use cursor() function to create a cursor  Cursor_name = connectionObject.cursor( )  For e.g. mycursor = mycon.cursor()  TO EXECUTE QUERY  We use execute( ) function to send query to connection  Cursor_name.execute(query)  For e.g. mycursor.execute(“select * from emp ) ‟
  • 12. Example - Cursor Output shows cursor is created and query is fired and stored, but no data is coming. T o fetch data we have to use functions like fetchall( ), fetchone( ), fetchmany( ) are used.
  • 15. Fetchall( ) – method extracts all rows
  • 18. Inserting data in MySQL table from Python  INSERT and UPDATE operation are executed in the same way we execute SELECT query using execute( ) but one thing to remember, after executing DML Commands -insert or update or delete query we must commit our query using connection object with commit( ).  For e.g. (if our connection object nameis mycon) mycon.commit( )
  • 19. Example : inserting data BEFORE PROGRAM EXECUTION AFTER PROGRAM EXECUTION
  • 21. Fetching(extracting) data from ResultSet  T o extract data from cursor following functions are used:  fetchall( ) : it will return all the record in the form of tuple.  fetchone( ) : it return one record from the result set. i.e. first time it will return first record, next time it will return second record and so on. If no more record it will return None.  fetchmany(n) : it will return n number of records. It no more record it will return an empty tuple.  rowcount: it will return number of rows retrieved from the cursor so far.
  • 29. Parameterized Query  We can pass values to query to perform dynamic search like we want to search for any employee number entered during runtime or to search any other column values.  T o Create Parameterized query we can use various methods like:  Concatenating dynamic variable to query values are entered.  String template with % formatting  String template with { } and format function in which
  • 31. String template with %s formatting  In this method we will use %s in place of values to substitute and then pass the value for that place.
  • 32. String template with %s formatting
  • 33. String template with { } and format( )  In this method in place of % s we will use { } and to pass values for these placeholder format( ) is used. Inside we can optionally give 0,1,2… values for e.g.  {0},{1} but its not mandatory. we can also optionally pass named parameter inside { } sothat while passing we need to pass. not to For e.g. values through format function remember the order of value {roll},{name} etc.
  • 34. String template with { } and format( )
  • 35. String template with { } and format()