SlideShare a Scribd company logo
Connecting Python with SQL
Database
OBJECTIVE
To make student
aware about
Connectivity between
frontend -backend
PREREQUISITE
➢Detailed knowledge of Python.
➢MySQL
Point to be
Focussed
(3 Important Steps)
➢ Download Python 3.5.3 and then install it
➢ Download MySQL API, exe file will be
downloaded install it.
➢ Install MySQL-Python Connector
➢ Now connect MySQL Server using
Python.
What is MySQLdb
What is Connection
What is a Cursor
•MySQLdb is an interface
for connecting to a MySQL
database server from
Python.
• It implements the Python
Database API and is built
on top of the MySQL C API.
• Just type the following in
your Python script and
execute it −
#!/usr/bin/python
import MySQLdb
What is MySQLdb
MySQLdb
import MySQldb
•The next step to using
MySQL in your Python
scripts is to make a
connection to the
database that you wish
to use. All Python DB-API
modules implement a
function
'module_name.connect‘
•This is the function that
is used to connect to the
database, in our case
MySQL..
What is Connection
Connection
MySQLdb
Db=MySQLdb.connect
(“localhost”, testuser”,
”test123”, ”TESTDB”)
Connecting to a MySQL database
:
db = MySQLdb.connect(host=MY_HOST, user=MY_USER, passwd=MY_PASS,
db=MY_DB)
Your Local
host
Your user
name
Your
Password
Name of the
Database
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
Create Cursor
cur=db.cursor()
•The next step is to create a
Cursor object.
•It will let you execute all the
queries you need
•In order to put our new
connnection to good use we
need to create a cursor
object.
•The cursor object is an
abstraction specified in the
Python DB-API
•It gives us the ability to
have multiple seperate
working environments
through the same
connection to the database.
•We can create a cursor by
executing the 'cursor'
function of your database
What is Cursor
Example of Simple Code to Connect MySQL with Python
<? xml version=“1.0” ?>
<land>
<forest>
<Tree>
---------------------------
---------------------------
---------------------------
</Tree>
</forest>
</land>
Creating database Table
➢Once a Database Connection is established, we are ready to create tables using execute( )
method of the created cursor
➢Example
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = “ “ "CREATE TABLE EMPLOYEE (FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )“ “ "
cursor.execute(sql)
# disconnect from server
db.close()
Insert Records into databse table
➢Its required to insert records in table for fetching records.
➢Example
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME)
VALUES('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Read Records (Select) into databse table
➢Read operation on any database means to fetch some useful
information from the database.
➢We can use fetchone() method to fetch single record
➢fetchall() method to fetch multiple values from a database table.
➢fetchone() − It fetches the next row of a query result set.
A result set is an object that is returned when a
cursor object is used to query a table.
fetchall() − It fetches all the rows in a result set.
If some rows have already been extracted from the
result set, then it retrieves the remaining rows from the
result set.
rowcount − This is a read-only attribute and returns the number of
rows that were affected by an execute() method.
➢Example
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE WHERE INCOME > '%d'" % (1000)
try:
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0] lname = row[1]
age = row[2] sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" %
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
# disconnect from server
db.close()
Update information into databse table
➢UPDATE Operation on any database means to update one or more records, which
are already available in the database.
➢The following procedure updates all the records having SEX as 'M'. Here, we
increase AGE of all the males by one year.
➢Example
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Delete information into databse table
➢DELETE operation is required when you want to delete some records from your
database. Following is the procedure to delete all the records from EMPLOYEE where
AGE is more than 20
➢Example
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
➢To disconnect Database connection,
use close() method.
db.close()
Disconnecting Database
Thank You

More Related Content

PPTX
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
PPTX
python db connection samples and program
PPTX
SQL-Connectivity python for beginners easy explanation with concepts and outp...
PPTX
015. Interface Python with sql interface ppt class 12
PPTX
PythonDatabaseAPI -Presentation for Database
PPTX
Interface Python with MySQLwedgvwewefwefwe.pptx
PPTX
MySql Interface database in sql python my.pptx
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
python db connection samples and program
SQL-Connectivity python for beginners easy explanation with concepts and outp...
015. Interface Python with sql interface ppt class 12
PythonDatabaseAPI -Presentation for Database
Interface Python with MySQLwedgvwewefwefwe.pptx
MySql Interface database in sql python my.pptx

Similar to PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx (20)

PPTX
Interface Python with MySQL connectivity.pptx
PDF
Interface Python with MySQL.pdf
PPTX
Database connectivity in python
PPTX
Database Connectivity using Python and MySQL
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
PDF
24. SQL .pdf
PPTX
Interfacing python to mysql (11363255151).pptx
PPTX
interface with mysql.pptx
PPTX
PYTHON MYSQL INTERFACE FOR CLASS XII STUDENTS
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
Mysql python
PPTX
Mysql python
PDF
AmI 2015 - Databases in Python
PDF
Interface python with sql database10.pdf
PPTX
Database connectivity in python
PDF
Develop Python Applications with MySQL Connector/Python
Interface Python with MySQL connectivity.pptx
Interface Python with MySQL.pdf
Database connectivity in python
Database Connectivity using Python and MySQL
Pyhton with Mysql to perform CRUD operations.pptx
24. SQL .pdf
Interfacing python to mysql (11363255151).pptx
interface with mysql.pptx
PYTHON MYSQL INTERFACE FOR CLASS XII STUDENTS
unit-5 SQL 1 creating a databse connection.pptx
Interface python with sql database.pdf--
Interface python with sql database.pdf
Mysql python
Mysql python
AmI 2015 - Databases in Python
Interface python with sql database10.pdf
Database connectivity in python
Develop Python Applications with MySQL Connector/Python
Ad

Recently uploaded (20)

PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
RMMM.pdf make it easy to upload and study
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Classroom Observation Tools for Teachers
human mycosis Human fungal infections are called human mycosis..pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Supply Chain Operations Speaking Notes -ICLT Program
Module 4: Burden of Disease Tutorial Slides S2 2025
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Anesthesia in Laparoscopic Surgery in India
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Pharma ospi slides which help in ospi learning
Final Presentation General Medicine 03-08-2024.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Sports Quiz easy sports quiz sports quiz
VCE English Exam - Section C Student Revision Booklet
Abdominal Access Techniques with Prof. Dr. R K Mishra
RMMM.pdf make it easy to upload and study
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Classroom Observation Tools for Teachers
Ad

PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx

  • 1. Connecting Python with SQL Database
  • 2. OBJECTIVE To make student aware about Connectivity between frontend -backend
  • 4. Point to be Focussed (3 Important Steps) ➢ Download Python 3.5.3 and then install it ➢ Download MySQL API, exe file will be downloaded install it. ➢ Install MySQL-Python Connector ➢ Now connect MySQL Server using Python.
  • 5. What is MySQLdb What is Connection What is a Cursor
  • 6. •MySQLdb is an interface for connecting to a MySQL database server from Python. • It implements the Python Database API and is built on top of the MySQL C API. • Just type the following in your Python script and execute it − #!/usr/bin/python import MySQLdb What is MySQLdb
  • 8. •The next step to using MySQL in your Python scripts is to make a connection to the database that you wish to use. All Python DB-API modules implement a function 'module_name.connect‘ •This is the function that is used to connect to the database, in our case MySQL.. What is Connection
  • 10. Connecting to a MySQL database : db = MySQLdb.connect(host=MY_HOST, user=MY_USER, passwd=MY_PASS, db=MY_DB) Your Local host Your user name Your Password Name of the Database db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
  • 12. •The next step is to create a Cursor object. •It will let you execute all the queries you need •In order to put our new connnection to good use we need to create a cursor object. •The cursor object is an abstraction specified in the Python DB-API •It gives us the ability to have multiple seperate working environments through the same connection to the database. •We can create a cursor by executing the 'cursor' function of your database What is Cursor
  • 13. Example of Simple Code to Connect MySQL with Python <? xml version=“1.0” ?> <land> <forest> <Tree> --------------------------- --------------------------- --------------------------- </Tree> </forest> </land>
  • 14. Creating database Table ➢Once a Database Connection is established, we are ready to create tables using execute( ) method of the created cursor ➢Example #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Drop table if it already exist using execute() method. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # Create table as per requirement sql = “ “ "CREATE TABLE EMPLOYEE (FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )“ “ " cursor.execute(sql) # disconnect from server db.close()
  • 15. Insert Records into databse table ➢Its required to insert records in table for fetching records. ➢Example #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES('Mac', 'Mohan', 20, 'M', 2000)""" try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
  • 16. Read Records (Select) into databse table ➢Read operation on any database means to fetch some useful information from the database. ➢We can use fetchone() method to fetch single record ➢fetchall() method to fetch multiple values from a database table. ➢fetchone() − It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table. fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves the remaining rows from the result set. rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method.
  • 17. ➢Example import MySQLdb db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) cursor = db.cursor() sql = "SELECT * FROM EMPLOYEE WHERE INCOME > '%d'" % (1000) try: cursor.execute(sql) # Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # Now print fetched result print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % (fname, lname, age, sex, income ) except: print "Error: unable to fecth data" # disconnect from server db.close()
  • 18. Update information into databse table ➢UPDATE Operation on any database means to update one or more records, which are already available in the database. ➢The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the males by one year. ➢Example import MySQLdb db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) cursor = db.cursor() sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: cursor.execute(sql) db.commit() except: db.rollback() db.close()
  • 19. Delete information into databse table ➢DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20 ➢Example import MySQLdb db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) cursor = db.cursor() sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) try: cursor.execute(sql) db.commit() except: db.rollback() db.close()
  • 20. ➢To disconnect Database connection, use close() method. db.close() Disconnecting Database