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 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()
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()
➢To disconnect Database connection,
use close() method.
db.close()
Disconnecting Database
Thank
You

More Related Content

Similar to python db connection samples and program (20)

PPTX
Database Connectivity using Python and MySQL
devsuchaye
 
PPT
PHP - Getting good with MySQL part II
Firdaus Adib
 
PPT
JDBC Connecticity.ppt
Swapnil Kale
 
PDF
RMySQL Tutorial For Beginners
Rsquared Academy
 
PPT
RESTful API In Node Js using Express
Jeetendra singh
 
PPTX
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
PPTX
Mysql python
Janu Jahnavi
 
PDF
Mysql python
Janu Jahnavi
 
PDF
Python my sql database connection
Learnbay Datascience
 
PPTX
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
PPTX
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
PPTX
Example R usage for oracle DBA UKOUG 2013
BertrandDrouvot
 
PDF
PerlApp2Postgresql (2)
Jerome Eteve
 
PPTX
Introduction databases and MYSQL
Naeem Junejo
 
PPTX
PHP mysql Introduction database
Mudasir Syed
 
PPT
Php classes in mumbai
aadi Surve
 
PDF
PHP with MySQL
wahidullah mudaser
 
PPTX
Postgres Conference (PgCon) New York 2019
Ibrar Ahmed
 
PPTX
Owasp Indy Q2 2012 Advanced SQLi
owaspindy
 
Database Connectivity using Python and MySQL
devsuchaye
 
PHP - Getting good with MySQL part II
Firdaus Adib
 
JDBC Connecticity.ppt
Swapnil Kale
 
RMySQL Tutorial For Beginners
Rsquared Academy
 
RESTful API In Node Js using Express
Jeetendra singh
 
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
Mysql python
Janu Jahnavi
 
Mysql python
Janu Jahnavi
 
Python my sql database connection
Learnbay Datascience
 
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Example R usage for oracle DBA UKOUG 2013
BertrandDrouvot
 
PerlApp2Postgresql (2)
Jerome Eteve
 
Introduction databases and MYSQL
Naeem Junejo
 
PHP mysql Introduction database
Mudasir Syed
 
Php classes in mumbai
aadi Surve
 
PHP with MySQL
wahidullah mudaser
 
Postgres Conference (PgCon) New York 2019
Ibrar Ahmed
 
Owasp Indy Q2 2012 Advanced SQLi
owaspindy
 

More from usha raj (19)

PPTX
sql12.pptxsql12.pptxsql12.pptxsql12.pptx
usha raj
 
PPTX
CSPPT_class12.pptxclass11_CS_control statements7
usha raj
 
PPTX
memory -team 2.pptxmemory -team 2.pptxmemory -team 2.pptxmemory -team 2.pptx
usha raj
 
PPTX
ComputerNEtWorksComplete.pptxComputerNEtWorksComplete.pptx
usha raj
 
PPTX
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
usha raj
 
PPTX
7-2-data-structures-ii-stacks-queues.pptx
usha raj
 
PPTX
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
usha raj
 
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
PPTX
APJ ABDUL KALAM (final draft).pptx sampl
usha raj
 
PPTX
BITCOIN PRICE PREDICTION USING MACHINE LEARNING.pptx
usha raj
 
PPTX
control-structure.pptxcontrol-structure.pptx
usha raj
 
PPTX
Cyber crimes and cyber security.pptx filetx
usha raj
 
PPTX
ResultAnalysis_PT3_Sahodaya_24_25_Class1_to_12.pptx
usha raj
 
PPTX
ResultAnalysis_PreBoard_Sahodaya24-25.pptx
usha raj
 
PPTX
health and education presentation demonstration
usha raj
 
PPTX
Knee Osteoarthritis Detection and its Severity.pptx
usha raj
 
DOCX
Supporting schedule-management-plan-template-with-instructions
usha raj
 
DOC
Lut ls p_pv1_0
usha raj
 
PDF
Banking botreport
usha raj
 
sql12.pptxsql12.pptxsql12.pptxsql12.pptx
usha raj
 
CSPPT_class12.pptxclass11_CS_control statements7
usha raj
 
memory -team 2.pptxmemory -team 2.pptxmemory -team 2.pptxmemory -team 2.pptx
usha raj
 
ComputerNEtWorksComplete.pptxComputerNEtWorksComplete.pptx
usha raj
 
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
usha raj
 
7-2-data-structures-ii-stacks-queues.pptx
usha raj
 
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
usha raj
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
APJ ABDUL KALAM (final draft).pptx sampl
usha raj
 
BITCOIN PRICE PREDICTION USING MACHINE LEARNING.pptx
usha raj
 
control-structure.pptxcontrol-structure.pptx
usha raj
 
Cyber crimes and cyber security.pptx filetx
usha raj
 
ResultAnalysis_PT3_Sahodaya_24_25_Class1_to_12.pptx
usha raj
 
ResultAnalysis_PreBoard_Sahodaya24-25.pptx
usha raj
 
health and education presentation demonstration
usha raj
 
Knee Osteoarthritis Detection and its Severity.pptx
usha raj
 
Supporting schedule-management-plan-template-with-instructions
usha raj
 
Lut ls p_pv1_0
usha raj
 
Banking botreport
usha raj
 
Ad

Recently uploaded (20)

PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPTX
Quarter 1_PPT_PE & HEALTH 8_WEEK 3-4.pptx
ronajadolpnhs
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
Quarter 1_PPT_PE & HEALTH 8_WEEK 3-4.pptx
ronajadolpnhs
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Ad

python db connection samples and program

  • 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 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()
  • 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()
  • 20. ➢To disconnect Database connection, use close() method. db.close() Disconnecting Database