Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Python Module_5 Notes (Revised)

Uploaded by

kgaddigoudar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Module_5 Notes (Revised)

Uploaded by

kgaddigoudar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

PYTHON APPLICATION PROGRAMMING

Module-5

Network Programming & SQL with Python


• Networked programs
o Hyper Text Transport Protocol (HTTP)
o The Simple Web Browser
o Retrieving an image over HTTP
o Retrieving web pages with urllib
o Parsing HTML and scraping the web
o Parsing HTML using regular expressions
o Parsing HTML using BeautifulSoup
o Reading binary files using urllib
• Using Web Services
o eXtensible Markup Language (XML)
o Parsing XML
o Looping through nodes
o JavaScript Object Notation - JSON
o Parsing JSON
o Application Programming Interfaces
o Google geocoding web service
o Security and API usage.
• Using databases and SQL
o What is a database?
o Database concepts
o Database Browser for SQLite
o Creating a database table
o Structured Query Language summary
o Spidering Twitter using a database
o Basic data modelling
o Programming with multiple tables

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Networked Programs
• Network Programming involves, writing programs that communicate with other programs
across a computer network to share the data.
• Python provides various libraries to implement the network protocols.
• Python provides two levels of access to network services
o Low-Level Access
o High-Level Access
Low-Level Access:
o At low level, we can access the socket support of the operating system using Python
libraries. It allows to implement client and server.
High-Level Access
o Python also provides libraries to implement High level (Application-level) network
protocols HTTP, FTP, etc.

HyperText Transport Protocol - HTTP


o HTTP stands for HyperText Transfer Protocol
o HTTP is application layer protocol which is used to access the data on the World Wide Web
(www).
o The HTTP protocol can be used to transfer the data in the form of plain text, hypertext,
audio, video, and so on.
o Hypertext is structured text that uses logical links (hyperlinks) between nodes.
o HTTP is the protocol to exchange or transfer hypertext.
o To send request and to receive response, HTTP uses GET and POST methods
GET: This is the HTTP method used to request a resource from the server

Socket Programming
o Sockets are endpoints in bidirectional communication channel.
o The sockets (endpoints) can communicate within a process, between processes in the same
machine, or between the processes on the different machines.
o Single socket provides a two-way connection, ie we can both read from and write to the same
socket.
o The Python provides built-in library called socket to make network connections and to
access data over other sockets

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Creating the socket:


o To create socket, we have to use the python socket method from socket library(module).
Syntax of Socket
socket.socket(socket_family, socket_type)

Family Address family provides different types of addresses to designate


address to the socket. Mainly 2 families: AF_INET & PF_INET
AF_INET = Address Format, Internet
AF_INET refers to IP addresses from the internet (IP V4 or IP V6)

Type Type of transport layer protocol TCP or UDP.


SOCK_STREAM for TCP (connection-oriented protocols)
SOCK_DGRAM for UDP (connectionless protocols)

The Simple Web Browser


Program: To retrieve web pages using the Hypertext Transfer Protocol (HTTP).
import socket #import the socket library

#To create the socket


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Now to connect to the website (http port 80)


s.connect(('data.pr4e.org', 80))

#Creating request to web page by using GET method of HTTP protocol


cmd='GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'

#Data sent should be in bytes format, so convert from string to byte


cmd= cmd.encode()

#Now to send request to the server (website)


s.send(cmd)

#Creating variable of type byte to store the received data


new_data=b''
#Now to receive the data from server
while True:
data = s.recv(512) #receiving the data of 512 bytes chuncks
if (len(data) < 1): #if the data is less than 1 byte
break #comeout of the loop
new_data=new_data+data

#close the socket connection

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

s.close()

#Extract the content of the file


a=new_data.decode() #convert back to string
print(a)

Explanation:
To cerate socket and send the request
1. First to import the socket library
2. Create the socket using socket.socket () method
3. Now to connect to the website using connect () method
4. To send request to webpage:
i. First create request for the web page GET method of the HTTP and store it in
cmd variable.
ii. Data sent should be in bytes format, so convert from string to byte using encode () method
and again store back in cmd variable.
iii. Now send request stored in cmd variable to the server using send () method.
Note ; HTTP/1.0: This specifies the version of the HTTP protocol i.e HTTP version 1.0.
Here \r\n means next line and \r\n\r\n represents the end of HTTP header.
5. To receive the data from webpage
i. Create the one variable new_data of type byte to store the received data
ii. We have to receive the in 512-character chunks, so extract entire data we have to use
loop
6. Close the connection using close method

The various functions used:


1. socket.socket () :
The socket method from the socket library(module) is used to create the socket
2. connect () :By using this method client establishes a connection with server.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

3. send() : The send () method of Python's socket module is used to send data from one socket
to another socket.
4. encode() : The data sent should be in bytes format. String data can be converted to bytes by using the
encode() method
5. recv() : This function is used to receive the contents of the web page
6. close() : This function is used to close the socket connection

Retrieving the image over HTTP


import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


mysock.connect(('data.pr4e.org', 80))
cmd= 'GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n'
cmd=cmd.encode()
mysock.send(cmd)

picture = b""
while True:
data = mysock.recv(20)
if (len(data) < 1):
break
picture = picture + data

mysock.close()

pos = picture.find(b'\r\n\r\n') # To remove the header information


picture = picture[pos+4:]
print(picture)

fhand = open('Image1.jpg', 'wb') #To store the image in the jpeg form
fhand.write(picture)
fhand.close()

Explanation:
To cerate socket and send the request
1. First to import the socket library
2. Create the socket using socket.socket () method
3. Now to connect to the website using connect () method
4. Create request for the web page by using GET method of the HTTP protocol and store it in
cmd variable
5. Data sent should be in bytes format, so convert from string to byte using encode () method
and again store back in cmd variable

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

6. Now send request stored in cmd variable to the server using send () method
Here \r\n means next line and \r\n\r\n means one complete blank line.
It means we are sending the blank line (message) to server as request.
7. Create the one variable picture of type byte to store the received data
8. To fetch or receive the data:Once we send request, then write a loop to receive data in 512-
character chunks and prints the data. This is repeated until there is no more data to read.
9. Remove the header information
10. Store the image in the jpeg form

Retrieving the webpages using urllib


• Python has urllib library, which is used to handle the URLs.
• By using urllib, we can access or retrieve web page like any text file.
• By using urllib library, we can, send GET requests, receive data, parse data, and modify the
headers, error handling etc. urllib handles all these tasks related to HTTP protocol
• The urllib.request is default module used for opening HTTP URLs.
• The urllib library has many modules to handle the URLs.
o urllib.request : for opening and reading. To open the file: urllib.request.urlopen().
o urllib.parse: The URL parsing is used to split a URL string into its components.
o urllib.error : It is used to handle the errors. It raises the exception when error occurs

Program : To retrieve web pages using urllib


import urllib.request

file1 = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')

for line in file1:


line=line.decode()
print(line)

Explanation
o Open the web page using urllib.urlopen.
o Then we can treat webpage like a file and read through it using a for loop.
o When we run program, output will be only contents of the file. The headers are still
sent, but the urllib code consumes the headers and only returns the data to us.
Example: To write a program to retrieve the data and compute the frequency of each word
import urllib.request,
import urllib.parse,
import urllib.error

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

counts = dict()
file1 = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')

for line in file1:


words = line.decode().split()
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
Reading Binary Files using urllib
o Sometimes we want to retrieve image or video files, these types of files are binary files
o We can retrieve the content of such files and we can save this data in the local file in our hard
disk using urllib.
import urllib.request
import urllib.parse
import re
img=urllib.request.urlopen('http://data.pr4e.org/cover3.jpg').
s= img.read()

fhand = open('cover3.jpg', 'wb')


fhand.write(img)
fhand.close()
Explain in your own words

Parsing HTML and scraping the web


• One of the common uses of the urllib is to scrape the web.
• Web scraping involves fetching and extracting data from website (webpage). It can also look
for patterns in the pages.
• Example: Google search engine will look at the source of one web page and extract the links
to other pages and retrieve those pages, extracting links, and so on.
• Using this technique, Google also checks for the frequency of links to measure, how
“important” a page is and how high the page should appear in its search results.

Parsing HTML using Regular Expressions


• Sometimes, we want extract only few particular words or data or pattern from webpage.
• To extract the required information For, we have to parse HTML page
• We can use regular expression to parse the HTML page
• To parse HTML page, first we should know the pattern of an HTML file.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

(Regular expression: the expression which conations the word or pattern to be searched)

Sample HTML file

Here,
<h1> and </h1> are the beginning and end of header tags
<p> and </p> are the beginning and end of paragraph tags
<a> and </a> The URL link is mentioned between these two anchor tags
href : It indicates start of hyperlink

• From above, we can understand that, if we want to extract hyperlinks from webpage, then
regular expression should the href =http.
• Now let us create a regular expression as: href=http://.+?
• Here, .+? indicates that, search all possible smallest matching strings.

Program: To extract the URL from the webpage or HTML

import urllib.request
import urllib.parse
import re
url = “http://www.pyhton.org”
s = urllib.request.urlopen(url) #open the webpage
html = s.read() #read the the webpage
links = re.findall (b 'href="(http://.*?)’, html) #regular expression
for link in links:
print(link.decode())

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

USING WEB SERVICES


There are many formats which are used to exchange data across the web.

• XML (eXtensible Markup Language): Best suited for exchanging document-style data
• JSON (JavaScript Object Notation):To exchange dictionaries, lists, or other international
information with each other.
• CSV

eXtensible Markup Language (XML)

• XML is the markup language similar to HTML. It is structured and tag-based language
• This is mainly used to exchange or transmit the data across the web. It is most suitable
for exchanging document style data.
• The XML is similar to HTML, but the difference is, HTML has predefined tags, but in
XML, developer can create his own tags (user defined). That is why it is called
EXTENSIBLE
• XML is more structured than HTML.
• The most important part of XML are XML tags.
• Two important tags of XML are: start tag & end tag
• The content (data) or instructions have to be placed between these starts and stop tags.
• Start Tag: Every XML element or content begins with start-tag.
Example: <name>
• End Tag: Every element that has a start tag should end with an end-tag.
Note: end tag includes a ("/")
Example </name>
• Simple example for xml document

• We can think XML document as a tree structure. Here Player is top tag or root tag(node)
and other tags such as name, age are child elements.

Tree structure above XML code.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Parsing XML (To retrieve or extract the node present in the XML tree)
(Parsing means extracting the data from text)
• To parse XML document, first XML document has to be converted into Tree structure (Tree
of nodes) and then required node of the tree has to be extracted(parsed).
• To convert the XML into Tree structure, inbuilt functions of Element Tree library are used.
So, first we need to import Element Tree library (xml.etree.ElementTree)
• Mainly 3 functions of Element Tree library are used.
▪ fromstring(): It is used to convert XML code into a tree-structure (tree of XML
nodes.)
▪ find () function is used extract the node (value of the tag) from XML tree
▪ get () function is used to extract the attribute value.

Example:

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

ET.fromstring(data) => converts the XML data (stored in the data variable) into an Element Tree structure
(tree).

tree.find('name').text =>finds the <name> tag in the XML tree and returns its content ('Dhoni')

tree.find('age').text =>finds the <age> tag in the XML tree and returns its content ('40').

tree.find('runs').text => finds the <runs> tag in the XML tree and returns its text content ('15000').

tree.find('email').get('hide')=> finds the <email> tag in the XML tree and retrieves the value of the 'hide'
attribute ('yes' ).

XML code
data = '''
<Player>
<name>Dhoni</name>
<age> 40</age>
<runs> 15000</runs>
<birthplace>Ranchi <birthplace>
<email hide="yes"/> #here hide is attribute
<Player> '''

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Parsing of XML code:


import xml.etree.ElementTree as ET
tree = ET.fromstring(data)
Name= tree.find('name').text
Age= tree.find('age').text
Runs= tree.find(‘runs’).text
Attribute= tree.find('email').get('hide')

Printing the extracted data (nodes)


print(‘Name:’, Name)
print('Age:', Age)
print('Runs:', Runs)
print(‘Attribute: ', Attribute)) #here get function is used to get the value of attribute

Output:
Name:Dhoni
Age: 40
Runs: 15000
Birthplace: Ranchi
Attribute: yes

Importance of XML in Web Applications:


XML has several important web applications; such as
Web Publishing: By using XML, we can create interactive pages, which are used to display
information.
Searching: In XML, data is placed between tags, so it makes searching easy.
For example: Consider XML page containing information of different cricket players such as player
name, age, runs scored etc. Now if we search the pages with player name, then it will directly search
for name tags and retrieve related data
Independent Data Interchange: Almost all other programming languages can parse (extract data)
from XML. So, XML is highly used for interchanging data between web application using APIs.
Granular Updates: Updating Entire document makes process slow, as the entire document needs to
be refreshed from the server. In case of XML document, only the part (granular) of the document is
updated/uploaded.
Metadata Applications:
Assists in Data Assessments and Aggregation
Custom Tags

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

JavaScript Object Notation (JSON)

• JSON stands for Java Script Object Notation.


• It is a standard text-based data format based on JavaScript syntax.
• JSON format is inspired by syntax of python dictionaries and lists
• JSON is standard data format used to store and retrieve data.
• It is mainly used to transmit data in web applications
Syntax:
• It stores the data in form of key-value pair (similar to python dictionary).
• All the items are written within the curly {} braces. Each key-value pair is separated by
comma.
• The key should be of string, but value can be of any data type.
Example :
{
"Player":
{
"name": "Dhoni",
"age": " 40",
"runs": " 15000",
"birthplace": "Ranchi "
}
}

Nested JSON object


{
"Team":
{
"India":
{
"Player":
{
"name": "Dhoni",
"age": " 40",
"runs": " 15000",
"birthplace": "Ranchi "
}
}
}
}

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Note : JSON is simpler than XML and it directly maps to data structures of other programming
languages. This makes parsing and data extraction simpler compared to XML. So it is widely being
used in the IT industry

Parsing JSON
To parse the JSON document, first JSON data has to be converted into python dictionary. For this,
load() function of json library is used. Then we can extract the data from python dictionary

#store the JSON file in variable: data


data = '''
{
"Player":
{
"name": "Dhoni",
"age": " 40",
"runs": " 15000",
"birthplace": "Ranchi "
}
}
'''
import json
# Load (Convert) the JSON data into a Python dictionary
data_dict = json.loads(data)

# Now obtain data from the dictionary using keys


info = data_dict["Player"] #
name = info["name"]
age = info["age"]
runs = info["runs"]
birthplace = info["birthplace"]

# Print the extracted information


print("Name:", name)
print("Age:", age)
print("Runs:", runs)
print("Birthplace:", birthplace)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Application Programming Interface (API)

• We know that, we can exchange data between applications using HTTP, XML and JSON.
There should be some set of rules or contract between applications for smoother data
transfer.
• The contract or set of rules between application-to-application is called as Application
Program Interfaces or APIs.
• If program ‘X’ is using an API, then it publishes the APIs (ie rules). If other applications
want to access services provided by X, then these other applications must follow the rules of
X.
• When we are building programs, in our program if we include functionality, which can
access the services provided by other programs, then this approach is called Service-
Oriented Architecture or SOA.
• In SOA approach: our overall application makes use of the services of other applications.
• In non-SOA approach: The application is a single standalone application which contains all
of the code necessary to implement the application.
• When an application makes a set of services available over the web using API, we call these
web services
Example of SOA:
• We can go to a single web site and book the ticket for air-travel and also book hotel room.
• This is possible due to service-oriented Architecture.
• Similarly, the payment for the air-travel or hotel accommodation can be done using credit
card. Thus, there are various services available that are interconnected. These services are
responsible for handling air-booking-data, hotel-booking-data or credit card transaction

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Google Geo-coding Web Service

• Google map is very popular web service provided by Google. The web service allows us to
make use of their large database of geographic information.
• We can submit a geographic search string like “Bhagya Nagar” to their geocoding API.
Then Google returns the location details (Map containing nearby landmarks)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Database & SQL

Database
• Database is organised collection of data
• Database is system in which data is stored, manipulated and retrieved
• We can perform various operations on data when it is stored in database
• There are various database systems:
o oracle,
o MySQL,
o Microsoft SQL Server
o SQLite.
Concept of Database
• If the data is organised in the form of table, then it is called as relational database
• The tables consists of rows and columns.
• The tables are stored inside the database file and each record is stored in particular row and
column of the table.
• In database terminology: table is called relation; row is called tuple and column is called
attribute

SQL Basics (Summary)


(SQL:Structured query language):
• A database is an organized collection of interrelated data.
• To perform operations on databases, we have to use structured query language.
• SQL is a language which is used to interact with database. It is used for storing,
manipulating and retrieving the data in databases.
• The various data types in SQLite are
1. INTEGER 2. TEXT 3. BOOLEAN 4. FLOAT 5. VARCHAR 6. NUMERIC

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• Basic SQL commands

Command Meaning

CREATE TABLE To Create a new table


DROP TABLE Deletes table
SELECT To Extract data from database
INSERT INTO To Insert new data into a database
UPDATE To Update data in database
DELETE To Delete data from database

Syntax:

Example: Creating the Table, inserting, extracting and deleting data

1. Creating Table: CREATE TABLE command is used to create a new table.

CREATE TABLE Player (name VARCHAR, age INT, runs INT )

This command creates a table called as Player with the attributes(columns) name, age and
runs. The name is of character data type and age, runs are of Integer type

2. Inserting data: Data is inserted using INSERT INTO command


INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 35, 15000)

3. Extracting data: SELECT command is used to extract or fetch the data


SELECT * FROM Player #Retrieves all the data from the table Player
SELECT name, age FROM player #Retrieves only name and age

4. Updating value: UPDATE command is used to modify the existing data


UPDATE Player
SET age = 45 WHERE name = 'Dhoni‘

5. Deleting data: DELETE command is used to delete the particular record


DELETE FROM player WHERE name='Dhoni'
DELETE FROM player # delete all data

6. Deleting Table: DROP TABLE is used to delete the table.


DROP TABLE Player

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

SQLite with Python (Embedding SQL commands in Python)

Embedded SQL: Putting SQL queries into high-level languages (python or java) to get meaningful
& efficient output
• Python has inbuilt library sqlite3 to handle SQLite database.
• This library has methods connect (), execute (), cursor () and commit () to perform operations
on database
• To use Python to handle SQL database
i. First import the python library sqlite3
ii. To create the database: Use connect () method to Create the database (or database
object) and open (connect) it, if already existing, then directly open it.
(Note: connect means create and open)
iii. To create cursor object: Use cursor () method to create cursor object (file handle)
It acts as a file handle or intermediator
iv. To Execute: Execute the SQL commands using execute () method. By using this
method, we can execute the commands like CREATE TABLE, INSERT INTO etc
v. Confirmation: Confirm the execution by using commit method ()
vi. Close the connection (database): Use close() method to close database

Example1: Program to create the table

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘CREATE TABLE Player (name TEXT, age INT, runs INT)’) #create table
conn.close() # close the database or connection

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Example 2: Program to delete the table

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘DROP TABLE Player’) # Delete table
conn.commit() #It is for confirmation
conn.close() # close the database or connection

Example 3: Program to create the table and to insert the values

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘CREATE TABLE Player (name TEXT, age INT, runs INT)’) #create table
cur.execute (‘INSERT INTO Player (name, age, runs) VALUES ('Dhoni', 35, 15000)’)
conn.close() # close the database or connection

Example 4: Program to update or modify the values

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘UPDATE Player SET runs 20,000 WHERE ‘name’ = virat)
conn.commit() #It is for confirmation
conn.close() # close the database or connection

Example 5: Program to delete the data

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘DELETE FROM Player WHERE= ‘Dhoni’)
conn.commit() #It is for confirmation
conn.close() # close the database or connection

Example 6: Extracting and displaying the data

import sqlite3
conn=sqlite3.connect(‘cricket.db’) #create & open database by name cricket and store in variable conn
cur=conn.cursor() # creating the cursor object : cur
cur.execute (‘SELECT name, age FROM Player’)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

for row in cur


print(row[0])
print(row[1])
conn.close() # close the database or connection

Example 7

Write a program to create a Student database with a table consisting of student name and age.
Read n records from the user and insert them into database. Write queries to display all records
and to display the students whose age is 20.

import sqlite3

# Create database and connect to it


conn = sqlite3.connect('StudentDB.db')
cursor = conn.cursor()

# Creating Table
cursor.execute('CREATE TABLE Student (name TEXT, age INTEGER)')

# Get the number of records to insert


n = int(input("Enter number of records:"))

# Insert records into the table


for i in range(n):
name = input("Enter Name:")
age = int(input("Enter age:"))
cursor.execute('INSERT INTO Student (name, age) VALUES (?, ?)', (name, age))

# Commit the changes to the database


conn.commit()

# Retrieve and print all data from the table


cursor.execute('SELECT * FROM Student')
y1 = cursor.fetchall()
print(y1)

# Retrieve and print data where age is 20


cursor.execute('SELECT * FROM Student WHERE age=20')
y2 = cursor.fetchall()
print(y2)

# Close the database connection


conn.close()

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

#Explanation
• for-loop is used to take the user-input for student’s name and age. These data are inserted
into the table. Question mark acts as a placeholder for user-input variables.
• Later we use a method fetchall() to fetch all the values of the database. Then we display all
the records form the table in the form of tuples.

Prof. Sujay Gejji ECE, SGBIT, Belagavi

You might also like