SlideShare a Scribd company logo
Narendra Kumar (PGT-CS), PM SHRI KV.2 BSF, Indore
Introduction to Python –MySQL
Connectivity
How MySQL communicates with Python
Python
Application Database
Executing SQL
statements
Retrieving query results
Communicates through DB API
What is DB API?
The DB API provides a minimal standard for working with
databases structures and syntax from programming Language
such as Python, java wherever possible. This API includes the
following:
• Importing the API module.
• Acquiring a connection with the database.
• Issuing SQL statements and stored procedures.
• Closing the connection
You must download a separate DB API module for each database
you need to access. For example, if you need to access an Oracle
database as well as a MySQL database, you must download both
the Oracle and the MySQL database modules.
Python DB-API
The Python standard for database interfaces is the Python DB-API.
Most Python database interfaces adhere to this standard. We can choose the right
database for our application.
Python Database API supports a wide range of database servers such as : MySQL,
Microsoft SQL Server, Oracle, mSQL, PostgreSQL and many more.
Python DB-API is consists of Connection and Cursor data objects
• Connection data object – Various methods to establish connection and access
database.
• Cursor data object – Manipulates and retrieves data.
What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python.
It is a third-party driver that provides MySQL support for Python, compliant with the
Python DB API version 2.0.
The new MySQL Connector/Python component provides an interface to the same
Python API, and is built into the MySQL Server and supported by Oracle.
A User can execute DDL, DML, DCL and TCL commands in MySQL through
python.
How do I Install MySQLdb?
pip install mysql-connector-python
And now import MySQLdb in python program or type- import MySQLdb
on interactive mode. If there is no error, it means driver is installed
successfully.
Step for Database Connectivity
Import MySQL Library
• Establish connection between MySQL & Python Application
• Execute SQL Statements from Python.
• Commit Changes to database.
• Close connection.
• Error handling if any that may occur during this process.
Connection object
Connection Objects Description
close() Closes the connection to the database.
commit() Commits (saves) a transaction (i.e., interaction with a
database through SQL keywords and commands).
rollback() Exits a pending transaction without saving changes.
Returns the user to the beginning of the transaction.
cursor() Returns a new Cursor object or the current connection
To create a connection between the MySQL database and the python
application, the connect() method of mysql. connector module is used. Pass the
database details like HostName, username, and the database password in the
method call. The method returns the connection object.
Establishing connection
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost", user="root", passwd="sia@1928",
database="oracledb")
print (mycon) # Statement to print status of connection
If you get below output, it mean connection with MySQL database named ‘oracledb’
is established successfully.
================RESTART: F:PythonPrgdb_demo.py =================
<mysql.connector.connection.MySQLConnection object at 0x0321DAD0>
Location
of
MySQL
Username
of MySQL
Password
of
MySQL
Name of
MySQL
Database. #the connect() constructor creates a connection to the MySQL
server and returns a mycon object
Cursor object
Cursor Objects Description
rowcount Returns the number of rows retrieved by the last execute method call.
close() Closes the cursor object.
Execute
(sql, [parameters])
Executes a SQL statement. The SQL statement may be parametrized (i.
e. placeholders instead of SQL literals).
executemany (sql,
seq_of_parameters)
Executes a SQL command against all parameter sequences or
mappings found in the sequence sql.
Executescript
(sql_script)
This is a nonstandard convenience method for executing multiple SQL
statements at once. It issues a COMMIT statement first, then executes
the SQL script it gets as a parameter.
fetchone(),fetchall(), fetchmany() are also methods of Cursor object.
Cursors are created through the connection by cursor() method: they are bound to
the connection for the entire lifetime and all the SQL commands are executed in
the context of the database session wrapped by the connection.
Creating cursor object
We need to create the object of a class called cursor that allows Python code
to execute database command in a database session.
Cursors are created by the connection.cursor( ) method: they are bound to the
connection for the entire lifetime and all the commands are executed in the
context of the database session wrapped by the connection.
cursor=mycon.cursor()
Fetch data from database
To fetch data from any database means to retrieve information from
the database. MySQLdb provides multiple ways to retrieve data such
as:
fetchall(): Fetch all (remaining) rows of a query result, returning them
as a sequence of sequences (e.g. a list of tuples).
fetchmany(size): Fetch the next set of rows of a query result, returning
a sequence of sequences (e.g. a list of tuples) .It will return number of
rows that matches to the size argument.
fetchone(): Fetch the next row of a query result set, returning a single
sequence, or None when no more data is available.
These methods generally used with Select query to retrieve data from
Step for Database Connectivity with Python
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd="123456
78",database="oracledb")
cursor=mycon.cursor()
mycon.commit()
cursor.close()
mycon.close()
• Catch Exception if any that may occur during this process.
sqlcmd="""insert into username values(%s,%s,%s)"""
cursor.execute(sqlcmd,record)
Execute Insert query (Input from User)
Executes an SQL command against all parameter sequences or
mappings found in the sequence sql •
uname=input("Enter username=")
passw=input("Password=")
status=input ("Status- (Y/N)")
record=(uname,passw,status)
sqlcmd="""insert into username values(%s,%s,%s)"""
cursor.execute(sqlcmd, record)
mycon.commit()
It is always best practice to use parameterized query i.e. placeholders ( %s ) inside a
SQL statements that contain input from users. It is also required to use one
placeholder for every value passed to SQL Statement.
Placeholders
(one placeholder
for each value )
record is a collection holding values
received as input from user.
Example Code-1 (Inserting a record)
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd="12345678",data
base="oracledb")
uname=input("Enter username=")
passw=input("Password=")
status=input ("Status- (Y/N)")
record=(uname,passw,status)
if mycon.is_connected():
print("Connection to Database Successful:")
cursor=mycon.cursor()
sqlcmd="""insert into username values(%s,%s,%s)"""
cursor.execute(sqlcmd,record)
mycon.commit()
cursor.close()
mycon.close()
else:
print("Unable to setup Connection to Database Successful:")
Execute SQL query (Select)
We can execute the sql queries from python program using execute() method
associated with cursor object .
Examples –
"select * from employee where income > '%d'" % (1000)
cursor.execute("select * from username")
sqlQuery="""select * from username where userid = %s and status =%s""“
cursor.execute(sqlQuery, (uname, sts ))
QueryArgs = (uname,sts)
sqlQuery="""select * from username where userid = %s and status =%s""“
cursor.execute(sqlQuery,QueryArgs)
Example Code-2 (To Fetch Data)
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd=“12345678",database="oracledb")
uname=input("Enter Username:")
sts=input("Enter status")
record = (uname,sts)
try:
if mycon.is_connected():
print("Connection to Database Successful:")
cursor=mycon.cursor()
sqlQuery="""select * from username where userid = %s and status=%s"""
cursor.execute(sqlQuery,record)
resultset=cursor.fetchone()
count=cursor.rowcount
print("Total Records",count)
for row in resultset:
print(row)
else:
print("Unable to setup Connection to Database Successful:")
except mysql.connector.Error as error:
print("Failed to get record from database: {}".format(error))
finally:
# closing database connection.
if (mycon.is_connected()):
cursor.close()
mycon.close()
print("connection is closed")
Error Handling or
Exception handling in
python is done by try,
except and finally
statements.
An exception is an
event, which occurs
during the execution of
a program, that
disrupts the normal
flow of the program's
instructions..
Execute SQL query (update)
Executes an SQL command against all parameter sequences or mappings
found in the sequence sql .
record=( ‘N’ ,’Siya’)
sqlcmd="update username set status=%s where userid=%s"
cursor.execute(sqlcmd,record)
mycon.commit()
Example Code-3 (To Modify Record (s))
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd=“sia@1928",database="oracled
b")
uname=input("Enter username=")
status=input ("Status- (Y/N)")
record=(uname,status)
if mycon.is_connected():
print("Connection to Database Successful:")
cursor=mycon.cursor()
sqlcmd="update username set status=%s where userid=%s"
cursor.execute(sqlcmd,record)
mycon.commit()
cursor.close()
mycon.close()
else:
print("Unable to setup Connection to Database Successful:")
Execute SQL query (Delete)
Executes an SQL command against all parameter sequences or mappings
found in the sequence sql •
record=( ‘N’ ,’Siya’)
sqlcmd=“delete from username where status=%s and userid=%s"
cursor.execute(sqlcmd,record)
mycon.commit()
Example Code-4 (To Delete Record (s))
import mysql.connector as sqlcnt
mycon=sqlcnt.connect(host="localhost",user="root",passwd="12345678",database="oracled
b")
uname=input("Enter username=")
status=input ("Status- (Y/N)")
record=(uname,status)
if mycon.is_connected():
print("Connection to Database Successful:")
cursor=mycon.cursor()
sqlcmd=“delete from username where status=%s and userid=%s"
cursor.execute(sqlcmd,record)
mycon.commit()
cursor.close()
mycon.close()
else:
print("Unable to setup Connection to Database Successful:")
THANK YOU

More Related Content

Similar to Database Connectivity using Python and MySQL (20)

24. SQL .pdf
24. SQL .pdf24. SQL .pdf
24. SQL .pdf
Bhavya103897
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Ado.net
Ado.netAdo.net
Ado.net
Iblesoft
 
Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
Deepika,Assistant Professor,PES College of Engineering ,Mandya
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
Fulvio Corno
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
Fulvio Corno
 
Interface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptxInterface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptx
BEENAHASSINA1
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
Fulvio Corno
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
jitendral
 
Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
MohammadImran709594
 
Interface python with sql database.pdf--
Interface python with sql database.pdf--Interface python with sql database.pdf--
Interface python with sql database.pdf--
jagaspeed09
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
DEEPIKA T
 
JDBC
JDBCJDBC
JDBC
Balwinder Kumar
 
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptxInterface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptx
AyushKumarXIthclass
 
Interface python with sql database10.pdf
Interface python with sql database10.pdfInterface python with sql database10.pdf
Interface python with sql database10.pdf
HiteshNandi
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
kamal kotecha
 
JDBC_Template for database connection using Spring
JDBC_Template for database connection using SpringJDBC_Template for database connection using Spring
JDBC_Template for database connection using Spring
gangishettysaikrishn
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
Mukesh Tekwani
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
Interface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptxInterface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptx
BEENAHASSINA1
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
Fulvio Corno
 
Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
MohammadImran709594
 
Interface python with sql database.pdf--
Interface python with sql database.pdf--Interface python with sql database.pdf--
Interface python with sql database.pdf--
jagaspeed09
 
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptxInterface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptx
AyushKumarXIthclass
 
Interface python with sql database10.pdf
Interface python with sql database10.pdfInterface python with sql database10.pdf
Interface python with sql database10.pdf
HiteshNandi
 
JDBC_Template for database connection using Spring
JDBC_Template for database connection using SpringJDBC_Template for database connection using Spring
JDBC_Template for database connection using Spring
gangishettysaikrishn
 

Recently uploaded (20)

Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Ad

Database Connectivity using Python and MySQL

  • 1. Narendra Kumar (PGT-CS), PM SHRI KV.2 BSF, Indore Introduction to Python –MySQL Connectivity
  • 2. How MySQL communicates with Python Python Application Database Executing SQL statements Retrieving query results Communicates through DB API
  • 3. What is DB API? The DB API provides a minimal standard for working with databases structures and syntax from programming Language such as Python, java wherever possible. This API includes the following: • Importing the API module. • Acquiring a connection with the database. • Issuing SQL statements and stored procedures. • Closing the connection You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules.
  • 4. Python DB-API The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard. We can choose the right database for our application. Python Database API supports a wide range of database servers such as : MySQL, Microsoft SQL Server, Oracle, mSQL, PostgreSQL and many more. Python DB-API is consists of Connection and Cursor data objects • Connection data object – Various methods to establish connection and access database. • Cursor data object – Manipulates and retrieves data.
  • 5. What is MySQLdb? MySQLdb is an interface for connecting to a MySQL database server from Python. It is a third-party driver that provides MySQL support for Python, compliant with the Python DB API version 2.0. The new MySQL Connector/Python component provides an interface to the same Python API, and is built into the MySQL Server and supported by Oracle. A User can execute DDL, DML, DCL and TCL commands in MySQL through python. How do I Install MySQLdb? pip install mysql-connector-python And now import MySQLdb in python program or type- import MySQLdb on interactive mode. If there is no error, it means driver is installed successfully.
  • 6. Step for Database Connectivity Import MySQL Library • Establish connection between MySQL & Python Application • Execute SQL Statements from Python. • Commit Changes to database. • Close connection. • Error handling if any that may occur during this process.
  • 7. Connection object Connection Objects Description close() Closes the connection to the database. commit() Commits (saves) a transaction (i.e., interaction with a database through SQL keywords and commands). rollback() Exits a pending transaction without saving changes. Returns the user to the beginning of the transaction. cursor() Returns a new Cursor object or the current connection To create a connection between the MySQL database and the python application, the connect() method of mysql. connector module is used. Pass the database details like HostName, username, and the database password in the method call. The method returns the connection object.
  • 8. Establishing connection import mysql.connector as sqlcnt mycon=sqlcnt.connect(host="localhost", user="root", passwd="sia@1928", database="oracledb") print (mycon) # Statement to print status of connection If you get below output, it mean connection with MySQL database named ‘oracledb’ is established successfully. ================RESTART: F:PythonPrgdb_demo.py ================= <mysql.connector.connection.MySQLConnection object at 0x0321DAD0> Location of MySQL Username of MySQL Password of MySQL Name of MySQL Database. #the connect() constructor creates a connection to the MySQL server and returns a mycon object
  • 9. Cursor object Cursor Objects Description rowcount Returns the number of rows retrieved by the last execute method call. close() Closes the cursor object. Execute (sql, [parameters]) Executes a SQL statement. The SQL statement may be parametrized (i. e. placeholders instead of SQL literals). executemany (sql, seq_of_parameters) Executes a SQL command against all parameter sequences or mappings found in the sequence sql. Executescript (sql_script) This is a nonstandard convenience method for executing multiple SQL statements at once. It issues a COMMIT statement first, then executes the SQL script it gets as a parameter. fetchone(),fetchall(), fetchmany() are also methods of Cursor object. Cursors are created through the connection by cursor() method: they are bound to the connection for the entire lifetime and all the SQL commands are executed in the context of the database session wrapped by the connection.
  • 10. Creating cursor object We need to create the object of a class called cursor that allows Python code to execute database command in a database session. Cursors are created by the connection.cursor( ) method: they are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection. cursor=mycon.cursor()
  • 11. Fetch data from database To fetch data from any database means to retrieve information from the database. MySQLdb provides multiple ways to retrieve data such as: fetchall(): Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). fetchmany(size): Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples) .It will return number of rows that matches to the size argument. fetchone(): Fetch the next row of a query result set, returning a single sequence, or None when no more data is available. These methods generally used with Select query to retrieve data from
  • 12. Step for Database Connectivity with Python import mysql.connector as sqlcnt mycon=sqlcnt.connect(host="localhost",user="root",passwd="123456 78",database="oracledb") cursor=mycon.cursor() mycon.commit() cursor.close() mycon.close() • Catch Exception if any that may occur during this process. sqlcmd="""insert into username values(%s,%s,%s)""" cursor.execute(sqlcmd,record)
  • 13. Execute Insert query (Input from User) Executes an SQL command against all parameter sequences or mappings found in the sequence sql • uname=input("Enter username=") passw=input("Password=") status=input ("Status- (Y/N)") record=(uname,passw,status) sqlcmd="""insert into username values(%s,%s,%s)""" cursor.execute(sqlcmd, record) mycon.commit() It is always best practice to use parameterized query i.e. placeholders ( %s ) inside a SQL statements that contain input from users. It is also required to use one placeholder for every value passed to SQL Statement. Placeholders (one placeholder for each value ) record is a collection holding values received as input from user.
  • 14. Example Code-1 (Inserting a record) import mysql.connector as sqlcnt mycon=sqlcnt.connect(host="localhost",user="root",passwd="12345678",data base="oracledb") uname=input("Enter username=") passw=input("Password=") status=input ("Status- (Y/N)") record=(uname,passw,status) if mycon.is_connected(): print("Connection to Database Successful:") cursor=mycon.cursor() sqlcmd="""insert into username values(%s,%s,%s)""" cursor.execute(sqlcmd,record) mycon.commit() cursor.close() mycon.close() else: print("Unable to setup Connection to Database Successful:")
  • 15. Execute SQL query (Select) We can execute the sql queries from python program using execute() method associated with cursor object . Examples – "select * from employee where income > '%d'" % (1000) cursor.execute("select * from username") sqlQuery="""select * from username where userid = %s and status =%s""“ cursor.execute(sqlQuery, (uname, sts )) QueryArgs = (uname,sts) sqlQuery="""select * from username where userid = %s and status =%s""“ cursor.execute(sqlQuery,QueryArgs)
  • 16. Example Code-2 (To Fetch Data) import mysql.connector as sqlcnt mycon=sqlcnt.connect(host="localhost",user="root",passwd=“12345678",database="oracledb") uname=input("Enter Username:") sts=input("Enter status") record = (uname,sts) try: if mycon.is_connected(): print("Connection to Database Successful:") cursor=mycon.cursor() sqlQuery="""select * from username where userid = %s and status=%s""" cursor.execute(sqlQuery,record) resultset=cursor.fetchone() count=cursor.rowcount print("Total Records",count) for row in resultset: print(row) else: print("Unable to setup Connection to Database Successful:") except mysql.connector.Error as error: print("Failed to get record from database: {}".format(error)) finally: # closing database connection. if (mycon.is_connected()): cursor.close() mycon.close() print("connection is closed") Error Handling or Exception handling in python is done by try, except and finally statements. An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions..
  • 17. Execute SQL query (update) Executes an SQL command against all parameter sequences or mappings found in the sequence sql . record=( ‘N’ ,’Siya’) sqlcmd="update username set status=%s where userid=%s" cursor.execute(sqlcmd,record) mycon.commit()
  • 18. Example Code-3 (To Modify Record (s)) import mysql.connector as sqlcnt mycon=sqlcnt.connect(host="localhost",user="root",passwd=“sia@1928",database="oracled b") uname=input("Enter username=") status=input ("Status- (Y/N)") record=(uname,status) if mycon.is_connected(): print("Connection to Database Successful:") cursor=mycon.cursor() sqlcmd="update username set status=%s where userid=%s" cursor.execute(sqlcmd,record) mycon.commit() cursor.close() mycon.close() else: print("Unable to setup Connection to Database Successful:")
  • 19. Execute SQL query (Delete) Executes an SQL command against all parameter sequences or mappings found in the sequence sql • record=( ‘N’ ,’Siya’) sqlcmd=“delete from username where status=%s and userid=%s" cursor.execute(sqlcmd,record) mycon.commit()
  • 20. Example Code-4 (To Delete Record (s)) import mysql.connector as sqlcnt mycon=sqlcnt.connect(host="localhost",user="root",passwd="12345678",database="oracled b") uname=input("Enter username=") status=input ("Status- (Y/N)") record=(uname,status) if mycon.is_connected(): print("Connection to Database Successful:") cursor=mycon.cursor() sqlcmd=“delete from username where status=%s and userid=%s" cursor.execute(sqlcmd,record) mycon.commit() cursor.close() mycon.close() else: print("Unable to setup Connection to Database Successful:")