SlideShare a Scribd company logo
Computer Science
Class XII ( As per CBSE Board)
Chapter 10
Interface python
with
SQL Database
Visit : python.mykvs.in for regular updates
As per Term
wise
Syllabus
2021-22
Interface python
with SQL Database
Visit : python.mykvs.in for regular updates
A database is nothing but an organized collection of data. Data is organized into rows,
columns and tables and it is indexed to make it easier to find relevant information. All
companies whether large or small use databases. So it become necessary to develop
project/software using any programming language like python in such a manner which can
interface with such databases which support SQL.Generalised form of Interface of python
with SQL Database can be understood with the help of this diagram.
Using SQL in any of the dbms ,databases and table can be created and data can be accessed,
updated and maintained. The Python standard for database interfaces is the Python DB-API.
Python Database API supports a wide range of database servers, like msql , mysql,
postgressql, Informix, oracle, Sybase etc.
Form/any user interface designed in any
programming language is Front End where
as data given by database as response is
known as Back-End database.SQL is just a
query language, it is not a database. To
perform SQL queries, we need to install any
database for example Oracle, MySQL,
MongoDB, PostGres SQL, SQL Server, DB2 et.
Why choose Python for database programming
Following are the reason to choose python for database
programming
• Programming more efficient and faster compared to other
languages.
• Portability of python programs.
• Support platform independent program development.
• Python supports SQL cursors.
• Python itself take care of open and close of connections.
• Python supports relational database systems.
• Porting of data from one dbms to other is easily possible as it
support large range of APIs for various databases.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
SQL Connectors
We must download a separate DB API module for each database we
need to access. Suppose we need to access an Oracle database as
well as a MySQL database, we must download both the Oracle and
the MySQL database modules .
The DB API provides a minimal standard for working with databases
using Python structures and syntax 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
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
Here we are using mysql as back end database because of it is open source,free
and portable and widely used. Any one of mysql-connector or MySQLdb can be
used for database programming.
1. mysql-connector
MySQL-Connector enables Python programs to access MySQL databases, using an
API that is compliant with the Python Database API Specification v2.0 (PEP 249). It
is written in pure Python and does not have any dependencies except for the
Python Standard Library.
Steps to use mysql-connector
1. Download Mysql API ,exe file and install it.(click here to download)
2. Install Mysql-Python Connector (Open command prompt and execute
command) >pip install mysql-connector
3. Now connect Mysql server using python
4. Write python statement in python shell import mysql.connector
If no error message is shown means mysql connector is properly installed
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
2. MySQLdb
MySQLdb is an interface for connecting to a MySQL database server from Python.
It implements the Python Database API v2.0 and is built on top of the MySQL C
API.
Steps to use mysqlclient
1. First Upgrade pip command through > python –m pip install –upgrade pip
2. Install mysqlclient through pip install mysqlclient
3. After successful installation check through import mysqldb
4. If it is installed no error will be displayed otherwise error message will be displayed
To install MySQLdb module, use the following command −
For Ubuntu, use the following command -
$ sudo apt-get install python-pip python-dev libmysqlclient-dev
For Fedora, use the following command -
$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gc c
For Python command prompt, use the following command -
pip install MySQL-python
Note − Make sure you have root privilege to install above module
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
Establish connection
For database interface/database programming ,connection must be established.Before
establishing connection there must be mysql installed on the system and a database and
table is already created.In following way we can establish a connection with mysql
database through mysql.connector.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root“,database=“school”)
print(mydb)
Alternatively we can write the following statement if we are using mysqldb
import MySQLdb
mydb = MySQLdb.connect("localhost",“root",“root",“school" )
print(mydb)
In both way we are specifying host,user,password and database name as
arguments.database is optional argument if we want to create database through
programming later on.
After successful execution of above statements in python following out will be displayed
<mysql.connector.connection.MySQLConnection object at 0x022624F0>
Otherwise an error message will be shown.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
Cursor object :
The MySQLCursor class instantiates objects that can execute operations such as SQL
statements. Cursor objects interact with the MySQL server using a MySQLConnection
object.
How to create cursor object and use it
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("create database if not exists school")
mycursor.execute("show databases")
for x in mycursor:
print(x)
Through line 4 we are creating a database named school if it is already not created with
the help of cursor object.
Line 5 executes the sql query show databases and store result in mycursor as collection
,whose values are being fetched in x variable one by one.
On execution of above program school database is created and a list of available databases
is shown.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
How to create table at run time
Table creation is very easy ,if we are already well versed in sql table creation then
we have to just pass the create table query in execute() method of cursor object.
But before table creation we must open the database.Here we are opening
database school(through connect() method) before student table creation.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",dat
abase="school")
mycursor=mydb.cursor()
mycursor.execute("create table student(rollno int(3) primary key,name
varchar(20),age int(2))")
On successful execution of above program a table named student with three
fields rollno,name,age will be created in school database.
We can check student table in mysql shell also,if required.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
How to change table structure/(add,edit,remove colum of a table) at
run time
To modify the structure of the table we just have to use alter table
query.Below program will add a column mark in the student table.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd
="root",database="school")
mycursor=mydb.cursor()
mycursor.execute("alter table student add (marks int(3))")
mycursor.execute("desc student")
for x in mycursor:
print(x)
Above program will add a column marks in the table student and will
display the structure of the table
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
Interface python
with SQL Database
How to insert record in a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",databa
se="school")
mycursor=mydb.cursor()
while 1==1:
ch=int(input("enter -1 to exit any other no to insert record into student table"))
if ch==-1:
break
rollno=int(input("Enter rollno"))
class1=int(input("Enter Class"))
name=input("Enter name")
marks=int(input("Enter marks"))
mycursor.execute("insert into student
values('"+str(rollno)+"','"+name+"','"+str(class1)+"','"+str(marks)+"')")
mydb.commit()
Visit : python.mykvs.in for regular updates
How to search records of a table at run time
Below statement demonstrate the use of select query for searching
specific record from a table.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="ro
ot",database="school")
mycursor=mydb.cursor()
nm=input("enter name")
mycursor.execute("select * from student where name='"+nm+"'")
for x in mycursor:
print (x)
Above statements will prompt a name from user,as user type the name
,that name is searched into the table student with the help of select query
.result will be shown with the help of mycursor collection.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
How to fetch all records of a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="ro
ot",database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchall()
for x in myrecords:
print (x)
MySQLCursor.fetchall() Method
The method fetches all (or all remaining) rows of a query result set and
returns a list of tuples. If no more rows are available, it returns an empty
list.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
How to fetch one record of a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="sc
hool")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
row=mycursor.fetchone()
while row is not None:
print(row)
row = mycursor.fetchone()
MySQLCursor.fetchone() Method
This method retrieves the next row of a query result set and returns a single sequence, or
None if no more rows are available. By default, the returned tuple consists of data
returned by the MySQL server, converted to Python objects.
MySQLCursor.fetchmany() Method
rows = cursor.fetchmany(size=1)
This method fetches the next set of rows of a query result and returns a list of tuples. If no
more rows are available, it returns an empty list.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
rowcount : Rows affected by Query. We can get number of rows affected by the query by
using rowcount. We will use one SELECT query here.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="s
chool")
mycursor=mydb.cursor()
mycursor = mydb.cursor(buffered=True)
mycursor.execute("select * from student")
noofrows=mycursor.rowcount
print("No of rows in student table are",noofrows)
buffered=True
We have used my_cursor as buffered cursor.
my_cursor = my_connect.cursor(buffered=True)
This type cursor fetches rows and buffers them after getting output from MySQL
database. We can use such cursor as iterator. There is no point in using buffered cursor for
single fetching of rows.If we don’t use buffered cursor then we will get -1 as output from
rowcount
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
How to delete record of a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="sc
hool")
mycursor=mydb.cursor()
mycursor.execute("delete from student where rollno=1")
mydb.commit()
In above program delete query will delete a record with rollno=1.commit() method is
necessary to call for database transaction.
How to update record of a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="sc
hool")
mycursor=mydb.cursor()
mycursor.execute("update student set marks=99 where rollno=2")
mydb.commit()
In above program update query update the marks with 99 of rollno=2
Students are advised to develop menu driven program using above concepts for better
understating of python mysql database interface.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
Manage Database Transaction
Database transaction represents a single unit of work. Any
operation which modifies the state of the MySQL database is a
transaction.
Python MySQL Connector provides the following method to manage
database transactions.
commit – MySQLConnection.commit() method sends a COMMIT
statement to the MySQL server, committing the current transaction.
rollback – MySQLConnection.rollback revert the changes made by
the current transaction.
AutoCommit – MySQLConnection.autocommit value can be
assigned as True or False to enable or disable the auto-commit
feature of MySQL. By default its value is False.
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database
Manage Database Transaction
try:
conn = mysql.connector.connect(host='localhost',database='school', user='root', password='root')
conn.autocommit = false
cursor = conn.cursor()
sql_update_query = """Update student set marks = 95 where rollno = 2"""
cursor.execute(sql_update_query)
print ("Record Updated successfully ")
#Commit your changes
conn.commit()
except mysql.connector.Error as error :
print("Failed to update record to database rollback: {}".format(error))
#reverting changes because of exception
conn.rollback()
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()
print("connection is closed")
In above program if update query is successfully executed then commit() method will be executed otherwise exception
error part will be executed where revert of update query will be done due to error.At finally we are closing cursor as
well as connection.To rollback or commit we have to set autocommit=false,just like conn.autocommit = false in above
program otherwise rollback will not work
Visit : python.mykvs.in for regular updates
Interface python
with SQL Database

More Related Content

What's hot (20)

BANKER'S ALGORITHM
BANKER'S ALGORITHMBANKER'S ALGORITHM
BANKER'S ALGORITHM
Muhammad Baqar Kazmi
 
Kernel (OS)
Kernel (OS)Kernel (OS)
Kernel (OS)
عطاءالمنعم اثیل شیخ
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
Protap Mondal
 
Operating system critical section
Operating system   critical sectionOperating system   critical section
Operating system critical section
Harshana Madusanka Jayamaha
 
Generations of Programming Languages
Generations of Programming LanguagesGenerations of Programming Languages
Generations of Programming Languages
Tarun Sharma
 
Semaphores
SemaphoresSemaphores
Semaphores
Mohd Arif
 
Interface specification
Interface specificationInterface specification
Interface specification
maliksiddique1
 
Unit05 dbms
Unit05 dbmsUnit05 dbms
Unit05 dbms
arnold 7490
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
Thai Pangsakulyanont
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
Rajendran
 
operating system structure
operating system structureoperating system structure
operating system structure
Waseem Ud Din Farooqui
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
Haresh Jaiswal
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
ASHOK KUMAR REDDY
 
Online examination system
Online examination systemOnline examination system
Online examination system
Mr. Vikram Singh Slathia
 
RTOS- Real Time Operating Systems
RTOS- Real Time Operating Systems RTOS- Real Time Operating Systems
RTOS- Real Time Operating Systems
Bayar shahab
 
Chapter 3 -Syntax Analyzer.ppt
Chapter 3 -Syntax Analyzer.pptChapter 3 -Syntax Analyzer.ppt
Chapter 3 -Syntax Analyzer.ppt
FamiDan
 
process control block
process control blockprocess control block
process control block
Vikas SHRIVASTAVA
 
Srs (Software Requirement Specification Document)
Srs (Software Requirement Specification Document) Srs (Software Requirement Specification Document)
Srs (Software Requirement Specification Document)
Fatima Qayyum
 
Theory of automata and formal language
Theory of automata and formal languageTheory of automata and formal language
Theory of automata and formal language
Rabia Khalid
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
MustafaIbrahimy
 

Similar to Interface python with sql database10.pdf (20)

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 sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
MohammadImran709594
 
unit-5 SQL 1 creating a databse connection.pptx
unit-5 SQL 1 creating a databse connection.pptxunit-5 SQL 1 creating a databse connection.pptx
unit-5 SQL 1 creating a databse connection.pptx
HuzaifaAhmedFarooqi
 
015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12
Shuvanth
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
interface with mysql.pptx
interface with mysql.pptxinterface with mysql.pptx
interface with mysql.pptx
KRITIKAOJHA11
 
Mysql python
Mysql pythonMysql python
Mysql python
Janu Jahnavi
 
Mysql python
Mysql pythonMysql python
Mysql python
Janu Jahnavi
 
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptxInterface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptx
AyushKumarXIthclass
 
python db connection samples and program
python db connection samples and programpython db connection samples and program
python db connection samples and program
usha raj
 
Interface Python with MySQL.pdf
Interface Python with MySQL.pdfInterface Python with MySQL.pdf
Interface Python with MySQL.pdf
DhirajKumarBiswal
 
SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...
harshitagrawal2608
 
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptxPYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
HistoryScienceWorld
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
MySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptxMySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptx
UshimArora
 
Chapter 6 Interface Python with MYSQL.pptx
Chapter 6 Interface Python with MYSQL.pptxChapter 6 Interface Python with MYSQL.pptx
Chapter 6 Interface Python with MYSQL.pptx
sarofba
 
AmI 2015 - Databases in Python
AmI 2015 - Databases in PythonAmI 2015 - Databases in Python
AmI 2015 - Databases in Python
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
 
Class 12 CS Ch-16 MySQL PPT.pptx
Class 12 CS Ch-16 MySQL PPT.pptxClass 12 CS Ch-16 MySQL PPT.pptx
Class 12 CS Ch-16 MySQL PPT.pptx
DeepaG66
 
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 sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
MohammadImran709594
 
unit-5 SQL 1 creating a databse connection.pptx
unit-5 SQL 1 creating a databse connection.pptxunit-5 SQL 1 creating a databse connection.pptx
unit-5 SQL 1 creating a databse connection.pptx
HuzaifaAhmedFarooqi
 
015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12015. Interface Python with sql interface ppt class 12
015. Interface Python with sql interface ppt class 12
Shuvanth
 
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 with mysql.pptx
interface with mysql.pptxinterface with mysql.pptx
interface with mysql.pptx
KRITIKAOJHA11
 
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptxInterface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptx
AyushKumarXIthclass
 
python db connection samples and program
python db connection samples and programpython db connection samples and program
python db connection samples and program
usha raj
 
Interface Python with MySQL.pdf
Interface Python with MySQL.pdfInterface Python with MySQL.pdf
Interface Python with MySQL.pdf
DhirajKumarBiswal
 
SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...SQL-Connectivity python for beginners easy explanation with concepts and outp...
SQL-Connectivity python for beginners easy explanation with concepts and outp...
harshitagrawal2608
 
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptxPYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
HistoryScienceWorld
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
MySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptxMySql Interface database in sql python my.pptx
MySql Interface database in sql python my.pptx
UshimArora
 
Chapter 6 Interface Python with MYSQL.pptx
Chapter 6 Interface Python with MYSQL.pptxChapter 6 Interface Python with MYSQL.pptx
Chapter 6 Interface Python with MYSQL.pptx
sarofba
 
AmI 2015 - Databases in Python
AmI 2015 - Databases in PythonAmI 2015 - Databases in Python
AmI 2015 - Databases in Python
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
 
Class 12 CS Ch-16 MySQL PPT.pptx
Class 12 CS Ch-16 MySQL PPT.pptxClass 12 CS Ch-16 MySQL PPT.pptx
Class 12 CS Ch-16 MySQL PPT.pptx
DeepaG66
 
Ad

Recently uploaded (17)

ARTIFICIAL INTELLIGENCE.pptx2565567765676
ARTIFICIAL INTELLIGENCE.pptx2565567765676ARTIFICIAL INTELLIGENCE.pptx2565567765676
ARTIFICIAL INTELLIGENCE.pptx2565567765676
areebaimtiazpmas
 
10 Latest Technologies and Their Benefits to End.pptx
10 Latest Technologies and Their Benefits to End.pptx10 Latest Technologies and Their Benefits to End.pptx
10 Latest Technologies and Their Benefits to End.pptx
EphraimOOghodero
 
Cloud VPS Provider in India: The Best Hosting Solution for Your Business
Cloud VPS Provider in India: The Best Hosting Solution for Your BusinessCloud VPS Provider in India: The Best Hosting Solution for Your Business
Cloud VPS Provider in India: The Best Hosting Solution for Your Business
DanaJohnson510230
 
HPC_Course_Presentation_No_Images included.pptx
HPC_Course_Presentation_No_Images included.pptxHPC_Course_Presentation_No_Images included.pptx
HPC_Course_Presentation_No_Images included.pptx
naziaahmadnm
 
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AIAI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
skdav34
 
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
Taqyea
 
Presentation About The Buttons | Selma SALTIK
Presentation About The Buttons | Selma SALTIKPresentation About The Buttons | Selma SALTIK
Presentation About The Buttons | Selma SALTIK
SELMA SALTIK
 
How to Make Money as a Cam Model – Tips, Tools & Real Talk
How to Make Money as a Cam Model – Tips, Tools & Real TalkHow to Make Money as a Cam Model – Tips, Tools & Real Talk
How to Make Money as a Cam Model – Tips, Tools & Real Talk
Cam Sites Expert
 
all Practical Project LAST summary note.docx
all Practical Project LAST summary note.docxall Practical Project LAST summary note.docx
all Practical Project LAST summary note.docx
seidjemal94
 
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdf
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdfEssential Tech Stack for Effective Shopify Dropshipping Integration.pdf
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdf
CartCoders
 
Networking concepts from zero to hero that covers the security aspects
Networking concepts from zero to hero that covers the security aspectsNetworking concepts from zero to hero that covers the security aspects
Networking concepts from zero to hero that covers the security aspects
amansinght675
 
Networking_Essentials_version_3.0_-_Module_7.pptx
Networking_Essentials_version_3.0_-_Module_7.pptxNetworking_Essentials_version_3.0_-_Module_7.pptx
Networking_Essentials_version_3.0_-_Module_7.pptx
elestirmen
 
basic to advance network security concepts
basic to advance network security conceptsbasic to advance network security concepts
basic to advance network security concepts
amansinght675
 
OSI_Security_Architecture Computer Science.pptx
OSI_Security_Architecture Computer Science.pptxOSI_Security_Architecture Computer Science.pptx
OSI_Security_Architecture Computer Science.pptx
faizanaseem873
 
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptxTransport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
ssuser80a7e81
 
Frontier Unlimited Internet Setup Step-by-Step Guide.pdf
Frontier Unlimited Internet Setup Step-by-Step Guide.pdfFrontier Unlimited Internet Setup Step-by-Step Guide.pdf
Frontier Unlimited Internet Setup Step-by-Step Guide.pdf
Internet Bundle Now
 
5 Reasons cheap WordPress hosting is costing you more | Reversed Out
5 Reasons cheap WordPress hosting is costing you more | Reversed Out5 Reasons cheap WordPress hosting is costing you more | Reversed Out
5 Reasons cheap WordPress hosting is costing you more | Reversed Out
Reversed Out Creative
 
ARTIFICIAL INTELLIGENCE.pptx2565567765676
ARTIFICIAL INTELLIGENCE.pptx2565567765676ARTIFICIAL INTELLIGENCE.pptx2565567765676
ARTIFICIAL INTELLIGENCE.pptx2565567765676
areebaimtiazpmas
 
10 Latest Technologies and Their Benefits to End.pptx
10 Latest Technologies and Their Benefits to End.pptx10 Latest Technologies and Their Benefits to End.pptx
10 Latest Technologies and Their Benefits to End.pptx
EphraimOOghodero
 
Cloud VPS Provider in India: The Best Hosting Solution for Your Business
Cloud VPS Provider in India: The Best Hosting Solution for Your BusinessCloud VPS Provider in India: The Best Hosting Solution for Your Business
Cloud VPS Provider in India: The Best Hosting Solution for Your Business
DanaJohnson510230
 
HPC_Course_Presentation_No_Images included.pptx
HPC_Course_Presentation_No_Images included.pptxHPC_Course_Presentation_No_Images included.pptx
HPC_Course_Presentation_No_Images included.pptx
naziaahmadnm
 
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AIAI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
AI REPLACING HUMANS /FATHER OF AI/BIRTH OF AI
skdav34
 
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
原版西班牙马拉加大学毕业证(UMA毕业证书)如何办理
Taqyea
 
Presentation About The Buttons | Selma SALTIK
Presentation About The Buttons | Selma SALTIKPresentation About The Buttons | Selma SALTIK
Presentation About The Buttons | Selma SALTIK
SELMA SALTIK
 
How to Make Money as a Cam Model – Tips, Tools & Real Talk
How to Make Money as a Cam Model – Tips, Tools & Real TalkHow to Make Money as a Cam Model – Tips, Tools & Real Talk
How to Make Money as a Cam Model – Tips, Tools & Real Talk
Cam Sites Expert
 
all Practical Project LAST summary note.docx
all Practical Project LAST summary note.docxall Practical Project LAST summary note.docx
all Practical Project LAST summary note.docx
seidjemal94
 
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdf
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdfEssential Tech Stack for Effective Shopify Dropshipping Integration.pdf
Essential Tech Stack for Effective Shopify Dropshipping Integration.pdf
CartCoders
 
Networking concepts from zero to hero that covers the security aspects
Networking concepts from zero to hero that covers the security aspectsNetworking concepts from zero to hero that covers the security aspects
Networking concepts from zero to hero that covers the security aspects
amansinght675
 
Networking_Essentials_version_3.0_-_Module_7.pptx
Networking_Essentials_version_3.0_-_Module_7.pptxNetworking_Essentials_version_3.0_-_Module_7.pptx
Networking_Essentials_version_3.0_-_Module_7.pptx
elestirmen
 
basic to advance network security concepts
basic to advance network security conceptsbasic to advance network security concepts
basic to advance network security concepts
amansinght675
 
OSI_Security_Architecture Computer Science.pptx
OSI_Security_Architecture Computer Science.pptxOSI_Security_Architecture Computer Science.pptx
OSI_Security_Architecture Computer Science.pptx
faizanaseem873
 
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptxTransport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
Transport Conjjjjjjjjjjjjjjjjjjjjjjjsulting by Slidesgo.pptx
ssuser80a7e81
 
Frontier Unlimited Internet Setup Step-by-Step Guide.pdf
Frontier Unlimited Internet Setup Step-by-Step Guide.pdfFrontier Unlimited Internet Setup Step-by-Step Guide.pdf
Frontier Unlimited Internet Setup Step-by-Step Guide.pdf
Internet Bundle Now
 
5 Reasons cheap WordPress hosting is costing you more | Reversed Out
5 Reasons cheap WordPress hosting is costing you more | Reversed Out5 Reasons cheap WordPress hosting is costing you more | Reversed Out
5 Reasons cheap WordPress hosting is costing you more | Reversed Out
Reversed Out Creative
 
Ad

Interface python with sql database10.pdf

  • 1. Computer Science Class XII ( As per CBSE Board) Chapter 10 Interface python with SQL Database Visit : python.mykvs.in for regular updates As per Term wise Syllabus 2021-22
  • 2. Interface python with SQL Database Visit : python.mykvs.in for regular updates A database is nothing but an organized collection of data. Data is organized into rows, columns and tables and it is indexed to make it easier to find relevant information. All companies whether large or small use databases. So it become necessary to develop project/software using any programming language like python in such a manner which can interface with such databases which support SQL.Generalised form of Interface of python with SQL Database can be understood with the help of this diagram. Using SQL in any of the dbms ,databases and table can be created and data can be accessed, updated and maintained. The Python standard for database interfaces is the Python DB-API. Python Database API supports a wide range of database servers, like msql , mysql, postgressql, Informix, oracle, Sybase etc. Form/any user interface designed in any programming language is Front End where as data given by database as response is known as Back-End database.SQL is just a query language, it is not a database. To perform SQL queries, we need to install any database for example Oracle, MySQL, MongoDB, PostGres SQL, SQL Server, DB2 et.
  • 3. Why choose Python for database programming Following are the reason to choose python for database programming • Programming more efficient and faster compared to other languages. • Portability of python programs. • Support platform independent program development. • Python supports SQL cursors. • Python itself take care of open and close of connections. • Python supports relational database systems. • Porting of data from one dbms to other is easily possible as it support large range of APIs for various databases. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 4. SQL Connectors We must download a separate DB API module for each database we need to access. Suppose we need to access an Oracle database as well as a MySQL database, we must download both the Oracle and the MySQL database modules . The DB API provides a minimal standard for working with databases using Python structures and syntax 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 Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 5. Here we are using mysql as back end database because of it is open source,free and portable and widely used. Any one of mysql-connector or MySQLdb can be used for database programming. 1. mysql-connector MySQL-Connector enables Python programs to access MySQL databases, using an API that is compliant with the Python Database API Specification v2.0 (PEP 249). It is written in pure Python and does not have any dependencies except for the Python Standard Library. Steps to use mysql-connector 1. Download Mysql API ,exe file and install it.(click here to download) 2. Install Mysql-Python Connector (Open command prompt and execute command) >pip install mysql-connector 3. Now connect Mysql server using python 4. Write python statement in python shell import mysql.connector If no error message is shown means mysql connector is properly installed Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 6. 2. MySQLdb MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API. Steps to use mysqlclient 1. First Upgrade pip command through > python –m pip install –upgrade pip 2. Install mysqlclient through pip install mysqlclient 3. After successful installation check through import mysqldb 4. If it is installed no error will be displayed otherwise error message will be displayed To install MySQLdb module, use the following command − For Ubuntu, use the following command - $ sudo apt-get install python-pip python-dev libmysqlclient-dev For Fedora, use the following command - $ sudo dnf install python python-devel mysql-devel redhat-rpm-config gc c For Python command prompt, use the following command - pip install MySQL-python Note − Make sure you have root privilege to install above module Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 7. Establish connection For database interface/database programming ,connection must be established.Before establishing connection there must be mysql installed on the system and a database and table is already created.In following way we can establish a connection with mysql database through mysql.connector. import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root“,database=“school”) print(mydb) Alternatively we can write the following statement if we are using mysqldb import MySQLdb mydb = MySQLdb.connect("localhost",“root",“root",“school" ) print(mydb) In both way we are specifying host,user,password and database name as arguments.database is optional argument if we want to create database through programming later on. After successful execution of above statements in python following out will be displayed <mysql.connector.connection.MySQLConnection object at 0x022624F0> Otherwise an error message will be shown. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 8. Cursor object : The MySQLCursor class instantiates objects that can execute operations such as SQL statements. Cursor objects interact with the MySQL server using a MySQLConnection object. How to create cursor object and use it import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root") mycursor=mydb.cursor() mycursor.execute("create database if not exists school") mycursor.execute("show databases") for x in mycursor: print(x) Through line 4 we are creating a database named school if it is already not created with the help of cursor object. Line 5 executes the sql query show databases and store result in mycursor as collection ,whose values are being fetched in x variable one by one. On execution of above program school database is created and a list of available databases is shown. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 9. How to create table at run time Table creation is very easy ,if we are already well versed in sql table creation then we have to just pass the create table query in execute() method of cursor object. But before table creation we must open the database.Here we are opening database school(through connect() method) before student table creation. import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",dat abase="school") mycursor=mydb.cursor() mycursor.execute("create table student(rollno int(3) primary key,name varchar(20),age int(2))") On successful execution of above program a table named student with three fields rollno,name,age will be created in school database. We can check student table in mysql shell also,if required. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 10. How to change table structure/(add,edit,remove colum of a table) at run time To modify the structure of the table we just have to use alter table query.Below program will add a column mark in the student table. import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd ="root",database="school") mycursor=mydb.cursor() mycursor.execute("alter table student add (marks int(3))") mycursor.execute("desc student") for x in mycursor: print(x) Above program will add a column marks in the table student and will display the structure of the table Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 11. Interface python with SQL Database How to insert record in a table at run time import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",databa se="school") mycursor=mydb.cursor() while 1==1: ch=int(input("enter -1 to exit any other no to insert record into student table")) if ch==-1: break rollno=int(input("Enter rollno")) class1=int(input("Enter Class")) name=input("Enter name") marks=int(input("Enter marks")) mycursor.execute("insert into student values('"+str(rollno)+"','"+name+"','"+str(class1)+"','"+str(marks)+"')") mydb.commit() Visit : python.mykvs.in for regular updates
  • 12. How to search records of a table at run time Below statement demonstrate the use of select query for searching specific record from a table. import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="ro ot",database="school") mycursor=mydb.cursor() nm=input("enter name") mycursor.execute("select * from student where name='"+nm+"'") for x in mycursor: print (x) Above statements will prompt a name from user,as user type the name ,that name is searched into the table student with the help of select query .result will be shown with the help of mycursor collection. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 13. How to fetch all records of a table at run time import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="ro ot",database="school") mycursor=mydb.cursor() mycursor.execute("select * from student") myrecords=mycursor.fetchall() for x in myrecords: print (x) MySQLCursor.fetchall() Method The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 14. How to fetch one record of a table at run time import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="sc hool") mycursor=mydb.cursor() mycursor.execute("select * from student") row=mycursor.fetchone() while row is not None: print(row) row = mycursor.fetchone() MySQLCursor.fetchone() Method This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects. MySQLCursor.fetchmany() Method rows = cursor.fetchmany(size=1) This method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 15. rowcount : Rows affected by Query. We can get number of rows affected by the query by using rowcount. We will use one SELECT query here. import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="s chool") mycursor=mydb.cursor() mycursor = mydb.cursor(buffered=True) mycursor.execute("select * from student") noofrows=mycursor.rowcount print("No of rows in student table are",noofrows) buffered=True We have used my_cursor as buffered cursor. my_cursor = my_connect.cursor(buffered=True) This type cursor fetches rows and buffers them after getting output from MySQL database. We can use such cursor as iterator. There is no point in using buffered cursor for single fetching of rows.If we don’t use buffered cursor then we will get -1 as output from rowcount Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 16. How to delete record of a table at run time import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="sc hool") mycursor=mydb.cursor() mycursor.execute("delete from student where rollno=1") mydb.commit() In above program delete query will delete a record with rollno=1.commit() method is necessary to call for database transaction. How to update record of a table at run time import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="sc hool") mycursor=mydb.cursor() mycursor.execute("update student set marks=99 where rollno=2") mydb.commit() In above program update query update the marks with 99 of rollno=2 Students are advised to develop menu driven program using above concepts for better understating of python mysql database interface. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 17. Manage Database Transaction Database transaction represents a single unit of work. Any operation which modifies the state of the MySQL database is a transaction. Python MySQL Connector provides the following method to manage database transactions. commit – MySQLConnection.commit() method sends a COMMIT statement to the MySQL server, committing the current transaction. rollback – MySQLConnection.rollback revert the changes made by the current transaction. AutoCommit – MySQLConnection.autocommit value can be assigned as True or False to enable or disable the auto-commit feature of MySQL. By default its value is False. Visit : python.mykvs.in for regular updates Interface python with SQL Database
  • 18. Manage Database Transaction try: conn = mysql.connector.connect(host='localhost',database='school', user='root', password='root') conn.autocommit = false cursor = conn.cursor() sql_update_query = """Update student set marks = 95 where rollno = 2""" cursor.execute(sql_update_query) print ("Record Updated successfully ") #Commit your changes conn.commit() except mysql.connector.Error as error : print("Failed to update record to database rollback: {}".format(error)) #reverting changes because of exception conn.rollback() finally: #closing database connection. if(conn.is_connected()): cursor.close() conn.close() print("connection is closed") In above program if update query is successfully executed then commit() method will be executed otherwise exception error part will be executed where revert of update query will be done due to error.At finally we are closing cursor as well as connection.To rollback or commit we have to set autocommit=false,just like conn.autocommit = false in above program otherwise rollback will not work Visit : python.mykvs.in for regular updates Interface python with SQL Database