SlideShare a Scribd company logo
UNIT V
UNIT V
Using Databases and SQL - Creating a database table -
Programming with multiple tables - Constraints in
database tables - Retrieve and/or insert a record - Storing
the friend relationship.
Visualizing data - Building a OpenStreetMap from
geocoded data.
USING DATABASES AND SQL
CREATING A DATABASE TABLE
SQLite is designed to be embedded into other
applications to provide database support within the
application.
When we create a database table we must tell the
database in advance the names of each of the columns in
the table and the type of data which we are planning to
store in each column.
The code to create a database file and a table named
Tracks with two columns in the database is as follows:
import sqlite3
conn = sqlite3.connect('music.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Tracks')
cur.execute('CREATE TABLE Tracks (title TEXT, plays
INTEGER)')
conn.close()
A cursor is like a file handle that we can use to perform
operations on the data stored in the database. Calling
cursor() is very similar conceptually to calling open() when
dealing with text files.
The database language is called Structured Query
Language or SQL for short.
import sqlite3
conn = sqlite3.connect('music.sqlite')
cur = conn.cursor()
cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)',
('Thunderstruck', 20))
cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)',
('My Way', 15))
conn.commit()
print('Tracks:')
cur.execute('SELECT title, plays FROM Tracks')
for row in cur:
print(row)
cur.execute('DELETE FROM Tracks WHERE plays < 100')
conn.commit()
cur.close()
The output of the program is as follows:
Tracks:
('Thunderstruck', 20)
('My Way', 15)
PROGRAMMING WITH MULTIPLE TABLES
The basic patterns are:
1. Create tables with primary keys and constraints.
2. When we have a logical key for a person (i.e., account
name) and we need the id value for the person,
depending on whether or not the person is already in the
People table we either need to:
look up the person in the People table and retrieve the id value
for the person or
add the person to the People table and get the id value for the
newly added row.
3. Insert the row that captures the “follows” relationship.
CONSTRAINTS IN DATABASE TABLES
cur.execute('''CREATE TABLE IF NOT EXISTS People (id
INTEGER PRIMARY KEY, name TEXT UNIQUE, retrieved
INTEGER)''')
cur.execute('''CREATE TABLE IF NOT EXISTS Follows
(from_id INTEGER, to_id INTEGER, UNIQUE(from_id,
to_id))''')
cur.execute('''INSERT OR IGNORE INTO People (name,
retrieved) VALUES ( ?, 0)''', ( friend, ) )
cur.execute('''INSERT OR IGNORE INTO Follows from_id,
to_id) VALUES (?, ?)''', (id, friend_id) )
RETRIEVE AND/OR INSERT A RECORD
 When we prompt the user for a Twitter account, if the
account exists, we must look up its id value. If the account
does not yet exist in the People table, we must insert the
record and get the id value from the inserted row.
friend = u['screen_name']
cur.execute('SELECT id FROM People WHERE name = ? LIMIT
1', (friend, ) )
try:
friend_id = cur.fetchone()[0]
countold = countold + 1
except:
cur.execute('''INSERT OR IGNORE INTO People (name, retrieved)
VALUES ( ?, 0)''', ( friend, ) )
conn.commit()
if cur.rowcount != 1 :
print('Error inserting account:',friend)
continue
friend_id = cur.lastrowid
countnew = countnew + 1
STORING THE FRIEND RELATIONSHIP
To insert the two numbers into the Follows table with the
following code:
cur.execute('INSERT OR IGNORE INTO Follows (from_id, to_id)
VALUES (?, ?)', (id, friend_id) )
Here is a sample execution of this program:
Enter a Twitter account, or quit:
No unretrieved Twitter accounts found
Enter a Twitter account, or quit: drchuck
Retrieving http://api.twitter.com/1.1/friends ...
New accounts= 20 revisited= 0
Enter a Twitter account, or quit:
Retrieving http://api.twitter.com/1.1/friends ...
New accounts= 17 revisited= 3
The following is the first few rows in the People and Follows tables after
this run is completed:
People:
(1, 'drchuck', 1)
(2, 'opencontent', 1)
(3, 'lhawthorn', 1)
(4, 'steve_coppin', 0)
(5, 'davidkocher', 0)
55 rows.
Follows:
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(1, 6)
60 rows.
VISUALIZING DATA
BUILDING A OPENSTREETMAP FROM GEOCODED DATA
In this project, we are using the OpenStreetMap
geocoding API to clean up some user-entered geographic
locations of university names and then placing the data
on an actual OpenStreetMap.
To get started, download the application from:
www.py4e.com/code3/opengeo.zip
In the first phase we take our input “survey” data in the file
where.data and read it one line at a time, and retrieve the
geocoded information from Google and store it in a
database geodata.sqlite.
You can restart the process at any time by removing the file
geodata.sqlite.
Run the geoload.py program. This program will read the input lines in
where.dataand for each line check to see if it is already in the
database.
If we don’t have the data for the location, it will call the geocoding API
to retrieve the data and store it in the database.
Here is a sample run after there is already some data in the database:
Found in database AGH University of Science and Technology
Found in database Academy of Fine Arts Warsaw Poland
Found in database American University in Cairo
Found in database Arizona State University
Found in database Athens Information Technology
Retrieving https://py4e-data.dr-chuck.net/
opengeo?q=BITS+Pilani
Retrieved 794 characters {"type":"FeatureColl
Retrieving https://py4e-data.dr-chuck.net/
opengeo?q=Babcock+University
Retrieved 760 characters {"type":"FeatureColl
Once you have some data loaded into geodata.sqlite, you
can visualize the data using the geodump.py program.
This program reads the database and writes the file where.js
with the location, latitude, and longitude in the form of
executable JavaScript code.
The file where.html consists of HTML and JavaScript to
visualize a Google map.
It reads the most recent data in where.js to get the data to be
visualized.
Simply open where.html in a browser to see the locations.
You can hover over each map pin to find the location that the
geocoding API returned for the user-entered input.
UNIT V PYTHON.pptx python basics ppt python

More Related Content

Similar to UNIT V PYTHON.pptx python basics ppt python (20)

PPT
Geek Austin PHP Class - Session 4
jimbojsb
 
PPTX
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
PPSX
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
PDF
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
Ortus Solutions, Corp
 
PPTX
3 PYTHON INTERACTION WITH SQLITE (concept of python)
AnamikaDhoundiyal
 
PDF
Local storage in Web apps
Ivano Malavolta
 
PPTX
Chapter -7.pptx
MikialeTesfamariam
 
PDF
AmI 2015 - Databases in Python
Fulvio Corno
 
PDF
Relationships are hard
ColdFusionConference
 
PDF
ORM in Django
Hoang Nguyen
 
PDF
Local Storage
Ivano Malavolta
 
PPTX
[Mas 500] Data Basics
rahulbot
 
PDF
The Django Book chapter 5 Models
Vincent Chien
 
DOCX
Sq lite
Revuru Bharadwaja
 
PPTX
Session #5 content providers
Vitali Pekelis
 
PPTX
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
PPTX
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
PPT
Lecture 15 - MySQL- PHP 1.ppt
TempMail233488
 
PPT
qwe.ppt
Heru762601
 
PDF
Hidden Treasures of the Python Standard Library
doughellmann
 
Geek Austin PHP Class - Session 4
jimbojsb
 
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
Ortus Solutions, Corp
 
3 PYTHON INTERACTION WITH SQLITE (concept of python)
AnamikaDhoundiyal
 
Local storage in Web apps
Ivano Malavolta
 
Chapter -7.pptx
MikialeTesfamariam
 
AmI 2015 - Databases in Python
Fulvio Corno
 
Relationships are hard
ColdFusionConference
 
ORM in Django
Hoang Nguyen
 
Local Storage
Ivano Malavolta
 
[Mas 500] Data Basics
rahulbot
 
The Django Book chapter 5 Models
Vincent Chien
 
Session #5 content providers
Vitali Pekelis
 
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Lecture 15 - MySQL- PHP 1.ppt
TempMail233488
 
qwe.ppt
Heru762601
 
Hidden Treasures of the Python Standard Library
doughellmann
 

Recently uploaded (20)

PDF
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
PPTX
Practice Gardens and Polytechnic Education: Utilizing Nature in 1950s’ Hu...
Lajos Somogyvári
 
PDF
Rapid Mathematics Assessment Score sheet for all Grade levels
DessaCletSantos
 
PDF
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
PDF
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
PDF
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
PPTX
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PPTX
Connecting Linear and Angular Quantities in Human Movement.pptx
AngeliqueTolentinoDe
 
PPTX
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
PDF
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
PDF
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
PPTX
week 1-2.pptx yueojerjdeiwmwjsweuwikwswiewjrwiwkw
rebznelz
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
How to Configure Refusal of Applicants in Odoo 18 Recruitment
Celine George
 
PPTX
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PPTX
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
PPTX
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
Practice Gardens and Polytechnic Education: Utilizing Nature in 1950s’ Hu...
Lajos Somogyvári
 
Rapid Mathematics Assessment Score sheet for all Grade levels
DessaCletSantos
 
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
Quiz Night Live May 2025 - Intra Pragya Online General Quiz
Pragya - UEM Kolkata Quiz Club
 
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
Connecting Linear and Angular Quantities in Human Movement.pptx
AngeliqueTolentinoDe
 
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
week 1-2.pptx yueojerjdeiwmwjsweuwikwswiewjrwiwkw
rebznelz
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
How to Configure Refusal of Applicants in Odoo 18 Recruitment
Celine George
 
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
Ad

UNIT V PYTHON.pptx python basics ppt python

  • 2. UNIT V Using Databases and SQL - Creating a database table - Programming with multiple tables - Constraints in database tables - Retrieve and/or insert a record - Storing the friend relationship. Visualizing data - Building a OpenStreetMap from geocoded data.
  • 4. CREATING A DATABASE TABLE SQLite is designed to be embedded into other applications to provide database support within the application. When we create a database table we must tell the database in advance the names of each of the columns in the table and the type of data which we are planning to store in each column.
  • 5. The code to create a database file and a table named Tracks with two columns in the database is as follows: import sqlite3 conn = sqlite3.connect('music.sqlite') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS Tracks') cur.execute('CREATE TABLE Tracks (title TEXT, plays INTEGER)') conn.close()
  • 6. A cursor is like a file handle that we can use to perform operations on the data stored in the database. Calling cursor() is very similar conceptually to calling open() when dealing with text files. The database language is called Structured Query Language or SQL for short.
  • 7. import sqlite3 conn = sqlite3.connect('music.sqlite') cur = conn.cursor() cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)', ('Thunderstruck', 20)) cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)', ('My Way', 15)) conn.commit() print('Tracks:') cur.execute('SELECT title, plays FROM Tracks') for row in cur: print(row) cur.execute('DELETE FROM Tracks WHERE plays < 100') conn.commit() cur.close()
  • 8. The output of the program is as follows: Tracks: ('Thunderstruck', 20) ('My Way', 15)
  • 10. The basic patterns are: 1. Create tables with primary keys and constraints. 2. When we have a logical key for a person (i.e., account name) and we need the id value for the person, depending on whether or not the person is already in the People table we either need to: look up the person in the People table and retrieve the id value for the person or add the person to the People table and get the id value for the newly added row. 3. Insert the row that captures the “follows” relationship.
  • 11. CONSTRAINTS IN DATABASE TABLES cur.execute('''CREATE TABLE IF NOT EXISTS People (id INTEGER PRIMARY KEY, name TEXT UNIQUE, retrieved INTEGER)''') cur.execute('''CREATE TABLE IF NOT EXISTS Follows (from_id INTEGER, to_id INTEGER, UNIQUE(from_id, to_id))''') cur.execute('''INSERT OR IGNORE INTO People (name, retrieved) VALUES ( ?, 0)''', ( friend, ) ) cur.execute('''INSERT OR IGNORE INTO Follows from_id, to_id) VALUES (?, ?)''', (id, friend_id) )
  • 12. RETRIEVE AND/OR INSERT A RECORD  When we prompt the user for a Twitter account, if the account exists, we must look up its id value. If the account does not yet exist in the People table, we must insert the record and get the id value from the inserted row.
  • 13. friend = u['screen_name'] cur.execute('SELECT id FROM People WHERE name = ? LIMIT 1', (friend, ) ) try: friend_id = cur.fetchone()[0] countold = countold + 1 except: cur.execute('''INSERT OR IGNORE INTO People (name, retrieved) VALUES ( ?, 0)''', ( friend, ) ) conn.commit() if cur.rowcount != 1 : print('Error inserting account:',friend) continue friend_id = cur.lastrowid countnew = countnew + 1
  • 14. STORING THE FRIEND RELATIONSHIP To insert the two numbers into the Follows table with the following code: cur.execute('INSERT OR IGNORE INTO Follows (from_id, to_id) VALUES (?, ?)', (id, friend_id) ) Here is a sample execution of this program: Enter a Twitter account, or quit: No unretrieved Twitter accounts found Enter a Twitter account, or quit: drchuck Retrieving http://api.twitter.com/1.1/friends ... New accounts= 20 revisited= 0 Enter a Twitter account, or quit: Retrieving http://api.twitter.com/1.1/friends ... New accounts= 17 revisited= 3
  • 15. The following is the first few rows in the People and Follows tables after this run is completed: People: (1, 'drchuck', 1) (2, 'opencontent', 1) (3, 'lhawthorn', 1) (4, 'steve_coppin', 0) (5, 'davidkocher', 0) 55 rows. Follows: (1, 2) (1, 3) (1, 4) (1, 5) (1, 6) 60 rows.
  • 17. BUILDING A OPENSTREETMAP FROM GEOCODED DATA In this project, we are using the OpenStreetMap geocoding API to clean up some user-entered geographic locations of university names and then placing the data on an actual OpenStreetMap. To get started, download the application from: www.py4e.com/code3/opengeo.zip In the first phase we take our input “survey” data in the file where.data and read it one line at a time, and retrieve the geocoded information from Google and store it in a database geodata.sqlite.
  • 18. You can restart the process at any time by removing the file geodata.sqlite. Run the geoload.py program. This program will read the input lines in where.dataand for each line check to see if it is already in the database. If we don’t have the data for the location, it will call the geocoding API to retrieve the data and store it in the database. Here is a sample run after there is already some data in the database: Found in database AGH University of Science and Technology Found in database Academy of Fine Arts Warsaw Poland Found in database American University in Cairo Found in database Arizona State University Found in database Athens Information Technology Retrieving https://py4e-data.dr-chuck.net/ opengeo?q=BITS+Pilani Retrieved 794 characters {"type":"FeatureColl Retrieving https://py4e-data.dr-chuck.net/ opengeo?q=Babcock+University Retrieved 760 characters {"type":"FeatureColl
  • 19. Once you have some data loaded into geodata.sqlite, you can visualize the data using the geodump.py program. This program reads the database and writes the file where.js with the location, latitude, and longitude in the form of executable JavaScript code. The file where.html consists of HTML and JavaScript to visualize a Google map. It reads the most recent data in where.js to get the data to be visualized. Simply open where.html in a browser to see the locations. You can hover over each map pin to find the location that the geocoding API returned for the user-entered input.