SlideShare a Scribd company logo
Priya B R
Assistant Professor
Christ Nagar College
Maranalloor
 Python allows us to connect to various databases through
database interfaces. Python’s database interface is DB-API.
You can choose the right database for your application.
Python Database API supports a wide range of database
servers such as −
 GadFly
 mSQL
 MySQL
 PostgreSQL
 Microsoft SQL Server 2000
 Informix
 Interbase
 Oracle
 Sybase
 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.
 Create a database called SAMPLE in MySQL.
 The user id and password used to access SAMPLE database
is “user” and “pass” respectively.
 Create a table STUDENT in SAMPLE.
 The table STUDENT has fields ROLLNO, NAME, AGE,
COURSE, GRADE.
 The following code shows how to connect MySQL database
with Python.
 import pymysql
 # Open database connection
 db = pymysql.connect("localhost","user",“pass",“SAMPLE" )
 # prepare a cursor object using cursor() method
 cursor = db.cursor()
 # execute SQL query using execute() method.
 cursor.execute("SELECT VERSION()")
 # Fetch a single row using fetchone() method.
 data = cursor.fetchone()
 print "Database version : “,data
 # disconnect from server
 db.close()
 Once a database connection is established, we are ready
to create tables or records into the database tables
using execute method of the created cursor.
 import pymysql
 # 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()I
 It is required when you want to create your records into a
database table.
 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)"""
 # 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()
 UPDATE Operation on any database means to update one
or more records, which are already available in the
database.
 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 UPDATE required records
 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'"
% ('M')
 # 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()
 DELETE operation is required when you want to delete
some records from your database.
 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 DELETE required records
 sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
 # 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()
 Transactions ensure the data consistency of the database. We
have to make sure that more than one applications must not
modify the records while performing the database operations.
The transactions have the following properties.
 Atomicity
Either the transaction completes, or nothing happens. If a
transaction contains 4 queries then all these queries must be
executed, or none of them must be executed.
 Consistency
The database must be consistent before the transaction starts
and the database must also be consistent after the transaction is
completed.
 Isolation
Intermediate results of a transaction are not visible outside the
current transaction.
 Durability
Once a transaction was committed, the effects are persistent,
even after a system failure.
 Commit is the operation, which gives a green
signal to database to finalize the changes,
and after this operation, no change can be
reverted back.
 db.commit()
 If you are not satisfied with one or more of
the changes and you want to revert back
those changes completely, then
use rollback() method.
 db.rollback()
 To disconnect Database connection, use
close() method.
 db.close()
 There are many sources of errors. A few examples are a syntax
error in an executed SQL statement, a connection failure, or
calling the fetch method for an already canceled or finished
statement handle.
 The DB API defines a number of errors that must exist in each
database module. The following table lists these exceptions.
 Warning
 Used for non-fatal issues. Must subclass StandardError.
 Error
 Base class for errors. Must subclass StandardError.
 InterfaceError
 Used for errors in the database module, not the database itself. Must
subclass Error.
 DatabaseError
 Used for errors in the database. Must subclass Error.
 DataError
 Subclass of DatabaseError that refers to errors in the data.
 There are many types of objects which can be used
with a for loop. We can use a for loop for iterating
through a list, string, dictionary or a file. These are
called iterable objects.
 The Python iterators object is initialized using
the iter() method. It uses the next() method for
iteration.
 __iter__(): The iter() method is called for the
initialization of an iterator. This returns an iterator
object
 __next__(): The next method returns the next value
for the iterable. When we use a for loop to traverse
any iterable object, internally it uses the iter()
method to get an iterator object, which further uses
the next() method to iterate over. This method raises
a StopIteration to signal the end of the iteration.
 Iterators can be materialized as lists or tuples by
using the list() or tuple() constructor functions.
 The following program shows how a list can be
converted to an iterator and then to materialize
to a tuple.
 list=[1,2,3]
 iterator=iter(list)
 t=tuple(iterator)
 print(t)
 Output
 (1,2,3)
 Often, when dealing with iterators, we also need
to keep a count of iterations. Python eases the
programmers’ task by providing a built-in
function enumerate() for this task. The
enumerate () method adds a counter to an
iterable and returns it in the form of an
enumerating object. This enumerated object can
then be used directly for loops or converted into
a list of tuples using the list() function.
 Syntax: enumerate(iterable, start=0)
 Parameters:
 Iterable: any object that supports iteration
 Start: the index value from which the counter is
to be started, by default it is 0
 Generators are a special class of functions that simplify the task
of writing iterators. Regular functions compute a value and
return it, but generators return an iterator that returns a stream
of values. A generator is a special routine that can be used to
control the iteration behaviour of a loop. A generator is similar to
a function returning an array.
 A generator has parameters, it can be called and it generates a
sequence of numbers. Function returns a whole array, a
generator yields one value at a time. Generators require less
memory
 Generators in Python
 are defined with the def keyword
 use the yield keyword
 may use several yield keywords
 returns an iterator
 When a function is called, a private namespace is allocated for
the local variables and when a function reaches a return
statement, the local variables are destroyed and the value is
returned to the caller.
 But in generators local variables aren’t thrown away on exiting a
function
 Decorators are used to add functionality to
an existing code.
 This is also called metaprogramming as a
part of the program tries to modify another
part of the program at compile time
 There are two types of decorators in Python
 Function decorators
 Class decorators
 A decorator in Python is any callable Python
object that is used to modify a function or a
class.
 The Common Gateway Interface(CGI) is a standard way for
a web server to pass a web user’s request to an application
program and to receive data back to forward to the user.
 The Common Gateway Interface, or CGI, is a set of
standards that define how information is exchanged
between the web server and a custom script.
 To understand the concept of CGI, let us see what happens
when we click a hyper link to browse a particular web
page or URL.
 Your browser contacts the HTTP web server and demands
for the URL, i.e., filename.
 Web Server parses the URL and looks for the filename. If it
finds that file then sends it back to the browser, otherwise
sends an error message indicating that you requested a
wrong file.
 Web browser takes response from web server and displays
either the received file or error message.
 All HTTP headers will be in the following
form:
 HTTP Field Name: Field Content
 Example
 Content-type: text/html
 Environment variables are a series of hidden
values that the web server sends to every CGI
program we run. Our program can parse them
and use the data they send. Environment
variables are stored in a hash named %ENV:.
Some of the environment variables are
 DOCUMENT_ROOT : The root directory of our
server.
 HTTP_COOKIE : The visitor’s cookie, if one is set.
 HTTP_HOST : The hostname of the page being
attempted.
 REMOTE_ADDR : The IP address of the visitor
 A form is an area that can contain form elements.
Form elements allow the user to enter information in
a form
 Get method
 The GET method is the default method to pass
information from browser to web server and it produces
a long string that appears in your browser's
Location:box. Never use GET method if you have
password or other sensitive information to pass to the
server.
 Post method
 A generally more reliable method of passing information
to a CGI program is the POST method. This packages the
information in exactly the same way as GET methods,
but instead of sending it as a text string after a ? in the
URL it sends it as a separate message.
 Radio Buttons are used when only one option is
required to be selected.
 Here is example HTML code for a form with two
radio buttons −
 <form action = "/cgi-bin/radiobutton.py" method
= "post" target = "_blank">
 <input type = "radio" name = "subject" value =
"maths" /> Maths
 <input type = "radio" name = "subject" value =
"physics" /> Physics
 <input type = "submit" value = "Select Subject" />
 </form>
 Drop Down Box is used when we have many
options available but only one or two will be
selected.
 Here is example HTML code for a form with one
drop down box −
 <form action = "/cgi-bin/dropdown.py" method =
"post" target = "_blank">
 <select name = "dropdown">
 <option value = "Maths" selected>Maths</option>
 <option value = "Physics">Physics</option>
</select> <input type = "submit" value =
"Submit"/>
 </form>
 Checkboxes are used when more than one option
is required to be selected.
 Here is example HTML code for a form with two
checkboxes −
 <form action = "/cgi-bin/checkbox.cgi" method =
"POST" target = "_blank">
 <input type = "checkbox" name = "maths" value =
"on" /> Maths
 <input type = "checkbox" name = "physics" value
= "on" /> Physics
 <input type = "submit" value = "Select Subject" />
 </form>
 TEXTAREA element is used when multiline
text has to be passed to the CGI Program.
 Here is example HTML code for a form with a
TEXTAREA box −
 <form action = "/cgi-bin/textarea.py"
method = "post" target = "_blank">
 <textarea name = "textcontent" cols = "40"
rows = "4"> Type your text here...
</textarea>
 <input type = "submit" value = "Submit" />
</form>
 An HTTP cookie is a small piece of data sent from a website and
stored on the user’s computer by the user’s web browser while
the user is browsing. Cookies are designed to be a reliable
mechanism for web sites to remember information or to record
the user’s browsing activity.
 Cookies are a plain text data record of 5 variable-length fields −
 Expires − The date the cookie will expire. If this is blank, the
cookie will expire when the visitor quits the browser.
 Domain − The domain name of your site.
 Path − The path to the directory or web page that sets the
cookie. This may be blank if you want to retrieve the cookie from
any directory or page.
 Secure − If this field contains the word "secure", then the cookie
may only be retrieved with a secure server. If this field is blank,
no such restriction exists.
 Name=Value − Cookies are set and retrieved in the form of key
and value pairs.
 To upload a file, the HTML form must have
the enctype attribute set to multipart/form-
data.
 The input tag with the file type creates a
"Browse" button.

More Related Content

Similar to 9 Python programming notes for ktu physics and computer application semester 4 (20)

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
 
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
 
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
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
Making use of Python 1st Edition Rashi Gupta
Making use of Python 1st Edition Rashi GuptaMaking use of Python 1st Edition Rashi Gupta
Making use of Python 1st Edition Rashi Gupta
jinzocrustag
 
Making use of Python 1st Edition Rashi Gupta
Making use of Python 1st Edition Rashi GuptaMaking use of Python 1st Edition Rashi Gupta
Making use of Python 1st Edition Rashi Gupta
nonsizueva
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
3 PYTHON INTERACTION WITH SQLITE (concept of python)
3 PYTHON  INTERACTION  WITH SQLITE (concept of python)3 PYTHON  INTERACTION  WITH SQLITE (concept of python)
3 PYTHON INTERACTION WITH SQLITE (concept of python)
AnamikaDhoundiyal
 
Interface Python with MySQL.pdf
Interface Python with MySQL.pdfInterface Python with MySQL.pdf
Interface Python with MySQL.pdf
DhirajKumarBiswal
 
Government Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxGovernment Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptx
ShivamDenge
 
Shivam PPT.pptx
Shivam PPT.pptxShivam PPT.pptx
Shivam PPT.pptx
ShivamDenge
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Return on Intelligence
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
Return on Intelligence
 
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptxInterface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptx
AyushKumarXIthclass
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Certified Professional Diploma in Data Science.pdf
Certified Professional Diploma in Data Science.pdfCertified Professional Diploma in Data Science.pdf
Certified Professional Diploma in Data Science.pdf
romanpaul8888
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
Interface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptxInterface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptx
BEENAHASSINA1
 
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
 
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
 
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
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
dharawagh9999
 
Making use of Python 1st Edition Rashi Gupta
Making use of Python 1st Edition Rashi GuptaMaking use of Python 1st Edition Rashi Gupta
Making use of Python 1st Edition Rashi Gupta
jinzocrustag
 
Making use of Python 1st Edition Rashi Gupta
Making use of Python 1st Edition Rashi GuptaMaking use of Python 1st Edition Rashi Gupta
Making use of Python 1st Edition Rashi Gupta
nonsizueva
 
3 PYTHON INTERACTION WITH SQLITE (concept of python)
3 PYTHON  INTERACTION  WITH SQLITE (concept of python)3 PYTHON  INTERACTION  WITH SQLITE (concept of python)
3 PYTHON INTERACTION WITH SQLITE (concept of python)
AnamikaDhoundiyal
 
Interface Python with MySQL.pdf
Interface Python with MySQL.pdfInterface Python with MySQL.pdf
Interface Python with MySQL.pdf
DhirajKumarBiswal
 
Government Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxGovernment Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptx
ShivamDenge
 
Interface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptxInterface Python with MySQLwedgvwewefwefwe.pptx
Interface Python with MySQLwedgvwewefwefwe.pptx
AyushKumarXIthclass
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Certified Professional Diploma in Data Science.pdf
Certified Professional Diploma in Data Science.pdfCertified Professional Diploma in Data Science.pdf
Certified Professional Diploma in Data Science.pdf
romanpaul8888
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
Interface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptxInterface Python with MySQL connectivity.pptx
Interface Python with MySQL connectivity.pptx
BEENAHASSINA1
 

Recently uploaded (20)

"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
wygalkelceqg
 
K-Circle-Weekly-Quiz-May2025_12345678910
K-Circle-Weekly-Quiz-May2025_12345678910K-Circle-Weekly-Quiz-May2025_12345678910
K-Circle-Weekly-Quiz-May2025_12345678910
PankajRodey1
 
Introduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdfIntroduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdf
CME4Life
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdfTechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup
 
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptxQUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
Sourav Kr Podder
 
POS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 SlidesPOS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 Slides
Celine George
 
Writing Research Papers: Guidance for Research Community
Writing Research Papers: Guidance for Research CommunityWriting Research Papers: Guidance for Research Community
Writing Research Papers: Guidance for Research Community
Rishi Bankim Chandra Evening College, Naihati, North 24 Parganas, West Bengal, India
 
Pragya Champion's Chalice 2025 Set , General Quiz
Pragya Champion's Chalice 2025 Set , General QuizPragya Champion's Chalice 2025 Set , General Quiz
Pragya Champion's Chalice 2025 Set , General Quiz
Pragya - UEM Kolkata Quiz Club
 
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesHow to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
Celine George
 
Order: Odonata Isoptera and Thysanoptera.pptx
Order: Odonata Isoptera and Thysanoptera.pptxOrder: Odonata Isoptera and Thysanoptera.pptx
Order: Odonata Isoptera and Thysanoptera.pptx
Arshad Shaikh
 
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
RVSPSOA
 
Exploring Identity Through Colombian Companies
Exploring Identity Through Colombian CompaniesExploring Identity Through Colombian Companies
Exploring Identity Through Colombian Companies
OlgaLeonorTorresSnch
 
How to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo SlidesHow to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo Slides
Celine George
 
Odoo 18 Point of Sale PWA - Odoo Slides
Odoo 18 Point of Sale PWA  - Odoo  SlidesOdoo 18 Point of Sale PWA  - Odoo  Slides
Odoo 18 Point of Sale PWA - Odoo Slides
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
Types of Actions in Odoo 18 - Odoo Slides
Types of Actions in Odoo 18 - Odoo SlidesTypes of Actions in Odoo 18 - Odoo Slides
Types of Actions in Odoo 18 - Odoo Slides
Celine George
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
wygalkelceqg
 
K-Circle-Weekly-Quiz-May2025_12345678910
K-Circle-Weekly-Quiz-May2025_12345678910K-Circle-Weekly-Quiz-May2025_12345678910
K-Circle-Weekly-Quiz-May2025_12345678910
PankajRodey1
 
Introduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdfIntroduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdf
CME4Life
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdfTechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.05.28.pdf
TechSoup
 
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptxQUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
Sourav Kr Podder
 
POS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 SlidesPOS Reporting in Odoo 18 - Odoo 18 Slides
POS Reporting in Odoo 18 - Odoo 18 Slides
Celine George
 
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesHow to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
Celine George
 
Order: Odonata Isoptera and Thysanoptera.pptx
Order: Odonata Isoptera and Thysanoptera.pptxOrder: Odonata Isoptera and Thysanoptera.pptx
Order: Odonata Isoptera and Thysanoptera.pptx
Arshad Shaikh
 
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
RVSPSOA
 
Exploring Identity Through Colombian Companies
Exploring Identity Through Colombian CompaniesExploring Identity Through Colombian Companies
Exploring Identity Through Colombian Companies
OlgaLeonorTorresSnch
 
How to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo SlidesHow to Use Owl Slots in Odoo 17 - Odoo Slides
How to Use Owl Slots in Odoo 17 - Odoo Slides
Celine George
 
Odoo 18 Point of Sale PWA - Odoo Slides
Odoo 18 Point of Sale PWA  - Odoo  SlidesOdoo 18 Point of Sale PWA  - Odoo  Slides
Odoo 18 Point of Sale PWA - Odoo Slides
Celine George
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
Types of Actions in Odoo 18 - Odoo Slides
Types of Actions in Odoo 18 - Odoo SlidesTypes of Actions in Odoo 18 - Odoo Slides
Types of Actions in Odoo 18 - Odoo Slides
Celine George
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
Ad

9 Python programming notes for ktu physics and computer application semester 4

  • 1. Priya B R Assistant Professor Christ Nagar College Maranalloor
  • 2.  Python allows us to connect to various databases through database interfaces. Python’s database interface is DB-API. You can choose the right database for your application. Python Database API supports a wide range of database servers such as −  GadFly  mSQL  MySQL  PostgreSQL  Microsoft SQL Server 2000  Informix  Interbase  Oracle  Sybase  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.
  • 3.  Create a database called SAMPLE in MySQL.  The user id and password used to access SAMPLE database is “user” and “pass” respectively.  Create a table STUDENT in SAMPLE.  The table STUDENT has fields ROLLNO, NAME, AGE, COURSE, GRADE.  The following code shows how to connect MySQL database with Python.  import pymysql  # Open database connection  db = pymysql.connect("localhost","user",“pass",“SAMPLE" )  # prepare a cursor object using cursor() method  cursor = db.cursor()  # execute SQL query using execute() method.  cursor.execute("SELECT VERSION()")  # Fetch a single row using fetchone() method.  data = cursor.fetchone()  print "Database version : “,data  # disconnect from server  db.close()
  • 4.  Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor.  import pymysql  # 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()I
  • 5.  It is required when you want to create your records into a database table.  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)"""  # 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()
  • 6.  UPDATE Operation on any database means to update one or more records, which are already available in the database.  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 UPDATE required records  sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')  # 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()
  • 7.  DELETE operation is required when you want to delete some records from your database.  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 DELETE required records  sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)  # 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()
  • 8.  Transactions ensure the data consistency of the database. We have to make sure that more than one applications must not modify the records while performing the database operations. The transactions have the following properties.  Atomicity Either the transaction completes, or nothing happens. If a transaction contains 4 queries then all these queries must be executed, or none of them must be executed.  Consistency The database must be consistent before the transaction starts and the database must also be consistent after the transaction is completed.  Isolation Intermediate results of a transaction are not visible outside the current transaction.  Durability Once a transaction was committed, the effects are persistent, even after a system failure.
  • 9.  Commit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.  db.commit()
  • 10.  If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback() method.  db.rollback()
  • 11.  To disconnect Database connection, use close() method.  db.close()
  • 12.  There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle.  The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.  Warning  Used for non-fatal issues. Must subclass StandardError.  Error  Base class for errors. Must subclass StandardError.  InterfaceError  Used for errors in the database module, not the database itself. Must subclass Error.  DatabaseError  Used for errors in the database. Must subclass Error.  DataError  Subclass of DatabaseError that refers to errors in the data.
  • 13.  There are many types of objects which can be used with a for loop. We can use a for loop for iterating through a list, string, dictionary or a file. These are called iterable objects.  The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.  __iter__(): The iter() method is called for the initialization of an iterator. This returns an iterator object  __next__(): The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object, which further uses the next() method to iterate over. This method raises a StopIteration to signal the end of the iteration.
  • 14.  Iterators can be materialized as lists or tuples by using the list() or tuple() constructor functions.  The following program shows how a list can be converted to an iterator and then to materialize to a tuple.  list=[1,2,3]  iterator=iter(list)  t=tuple(iterator)  print(t)  Output  (1,2,3)
  • 15.  Often, when dealing with iterators, we also need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. The enumerate () method adds a counter to an iterable and returns it in the form of an enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() function.  Syntax: enumerate(iterable, start=0)  Parameters:  Iterable: any object that supports iteration  Start: the index value from which the counter is to be started, by default it is 0
  • 16.  Generators are a special class of functions that simplify the task of writing iterators. Regular functions compute a value and return it, but generators return an iterator that returns a stream of values. A generator is a special routine that can be used to control the iteration behaviour of a loop. A generator is similar to a function returning an array.  A generator has parameters, it can be called and it generates a sequence of numbers. Function returns a whole array, a generator yields one value at a time. Generators require less memory  Generators in Python  are defined with the def keyword  use the yield keyword  may use several yield keywords  returns an iterator  When a function is called, a private namespace is allocated for the local variables and when a function reaches a return statement, the local variables are destroyed and the value is returned to the caller.  But in generators local variables aren’t thrown away on exiting a function
  • 17.  Decorators are used to add functionality to an existing code.  This is also called metaprogramming as a part of the program tries to modify another part of the program at compile time  There are two types of decorators in Python  Function decorators  Class decorators  A decorator in Python is any callable Python object that is used to modify a function or a class.
  • 18.  The Common Gateway Interface(CGI) is a standard way for a web server to pass a web user’s request to an application program and to receive data back to forward to the user.  The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.  To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL.  Your browser contacts the HTTP web server and demands for the URL, i.e., filename.  Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file.  Web browser takes response from web server and displays either the received file or error message.
  • 19.  All HTTP headers will be in the following form:  HTTP Field Name: Field Content  Example  Content-type: text/html
  • 20.  Environment variables are a series of hidden values that the web server sends to every CGI program we run. Our program can parse them and use the data they send. Environment variables are stored in a hash named %ENV:. Some of the environment variables are  DOCUMENT_ROOT : The root directory of our server.  HTTP_COOKIE : The visitor’s cookie, if one is set.  HTTP_HOST : The hostname of the page being attempted.  REMOTE_ADDR : The IP address of the visitor
  • 21.  A form is an area that can contain form elements. Form elements allow the user to enter information in a form  Get method  The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use GET method if you have password or other sensitive information to pass to the server.  Post method  A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message.
  • 22.  Radio Buttons are used when only one option is required to be selected.  Here is example HTML code for a form with two radio buttons −  <form action = "/cgi-bin/radiobutton.py" method = "post" target = "_blank">  <input type = "radio" name = "subject" value = "maths" /> Maths  <input type = "radio" name = "subject" value = "physics" /> Physics  <input type = "submit" value = "Select Subject" />  </form>
  • 23.  Drop Down Box is used when we have many options available but only one or two will be selected.  Here is example HTML code for a form with one drop down box −  <form action = "/cgi-bin/dropdown.py" method = "post" target = "_blank">  <select name = "dropdown">  <option value = "Maths" selected>Maths</option>  <option value = "Physics">Physics</option> </select> <input type = "submit" value = "Submit"/>  </form>
  • 24.  Checkboxes are used when more than one option is required to be selected.  Here is example HTML code for a form with two checkboxes −  <form action = "/cgi-bin/checkbox.cgi" method = "POST" target = "_blank">  <input type = "checkbox" name = "maths" value = "on" /> Maths  <input type = "checkbox" name = "physics" value = "on" /> Physics  <input type = "submit" value = "Select Subject" />  </form>
  • 25.  TEXTAREA element is used when multiline text has to be passed to the CGI Program.  Here is example HTML code for a form with a TEXTAREA box −  <form action = "/cgi-bin/textarea.py" method = "post" target = "_blank">  <textarea name = "textcontent" cols = "40" rows = "4"> Type your text here... </textarea>  <input type = "submit" value = "Submit" /> </form>
  • 26.  An HTTP cookie is a small piece of data sent from a website and stored on the user’s computer by the user’s web browser while the user is browsing. Cookies are designed to be a reliable mechanism for web sites to remember information or to record the user’s browsing activity.  Cookies are a plain text data record of 5 variable-length fields −  Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.  Domain − The domain name of your site.  Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page.  Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.  Name=Value − Cookies are set and retrieved in the form of key and value pairs.
  • 27.  To upload a file, the HTML form must have the enctype attribute set to multipart/form- data.  The input tag with the file type creates a "Browse" button.