Text stringlengths 1 9.41k |
|---|
In this example the criterion happens to apply to all the
rows so we empty the table out so we can run the program repeatedly. |
After the
DELETE is performed, we also call commit() to force the data to be removed from
the database.
##### 15.5 Structured Query Language summary
So far, we have been using the Structured Query Language in our Python examples
and have covered many of the basics of the SQL commands. |
In this section, we
look at the SQL language in particular and give an overview of SQL syntax.
Since there are so many different database vendors, the Structured Query Language
(SQL) was standardized so we could communicate in a portable manner to database
systems from multiple vendors.
-----
A relational database ... |
The columns
generally have a type such as text, numeric, or date data. |
When we create a table,
we indicate the names and types of the columns:
**CREATE TABLE Tracks (title TEXT, plays INTEGER)**
To insert a row into a table, we use the SQL INSERT command:
**INSERT INTO Tracks (title, plays) VALUES ('My Way', 15)**
The INSERT statement specifies the table name, then a list of the field... |
It also allows
an optional ORDER BY clause to control the sorting of the returned rows.
**SELECT * FROM Tracks WHERE title = 'My Way'**
Using * indicates that you want the database to return all of the columns for each
row that matches the WHERE clause.
Note, unlike in Python, in a SQL WHERE clause we use a single e... |
Other logical operations allowed
in a WHERE clause include <, >, <=, >=, !=, as well as AND and OR and parentheses
to build your logical expressions.
You can request that the returned rows be sorted by one of the fields as follows:
**SELECT title,plays FROM Tracks ORDER BY title**
To remove a row, you need a WHERE c... |
The
WHERE clause determines which rows are to be deleted:
**DELETE FROM Tracks WHERE title = 'My Way'**
It is possible to UPDATE a column or columns within one or more rows in a table
using the SQL UPDATE statement as follows:
**UPDATE Tracks SET plays = 16 WHERE title = 'My Way'**
The UPDATE statement specifies a ... |
A single UPDATE statement will change all of the rows that
match the WHERE clause. |
If a WHERE clause is not specified, it performs the UPDATE
on all of the rows in the table.
These four basic SQL commands (INSERT, SELECT, UPDATE, and DELETE)
allow the four basic operations needed to create and maintain data.
-----
##### 15.6 Spidering Twitter using a database
In this section, we will create a si... |
Note: Be very careful when running
_this program. |
You do not want to pull too much data or run the program for too_
_long and end up having your Twitter access shut off._
One of the problems of any kind of spidering program is that it needs to be able
to be stopped and restarted many times and you do not want to lose the data that
you have retrieved so far. |
You don’t want to always restart your data retrieval at
the very beginning so we want to store data as we retrieve it so our program can
start back up and pick up where it left off.
We will start by retrieving one person’s Twitter friends and their statuses, looping
through the list of friends, and adding each of the ... |
After we process one person’s Twitter friends, we check
in our database and retrieve one of the friends of the friend. |
We do this over and
over, picking an “unvisited” person, retrieving their friend list, and adding friends
we have not seen to our list for a future visit.
We also track how many times we have seen a particular friend in the database to
get some sense of their “popularity”.
By storing our list of known accounts and wh... |
It is based on the code from the exercise earlier in
the book that uses the Twitter API.
Here is the source code for our Twitter spidering application:
from urllib.request import urlopen
import urllib.error
import twurl
import json
import sqlite3
TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json'
conn = ... |
LIMIT 1',
(friend, ))
**try:**
count = cur.fetchone()[0]
cur.execute('UPDATE Twitter SET friends = ? |
WHERE name = ?',
(count+1, friend))
countold = countold + 1
**except:**
cur.execute('''INSERT INTO Twitter (name, retrieved, friends)
VALUES (?, 0, 1)''', (friend, ))
countnew = countnew + 1
print('New accounts=', countnew, ' revisited=', countold)
conn.commit()
cur.close()
_# Code: http://www.pythonlearn.com/code3... |
Each row in the Twitter table has a column for the account name,
whether we have retrieved the friends of this account, and how many times this
account has been “friended”.
In the main loop of the program, we prompt the user for a Twitter account name
or “quit” to exit the program. |
If the user enters a Twitter account, we retrieve
the list of friends and statuses for that user and add each friend to the database
if not already in the database. |
If the friend is already in the list, we add 1 to the
friends field in the row in the database.
-----
If the user presses enter, we look in the database for the next Twitter account that
we have not yet retrieved, retrieve the friends and statuses for that account, add
them to the database or update them, and increa... |
Then
we use the SELECT statement to see if we already have stored this particular
screen_name in the database and retrieve the friend count (friends) if the record
exists.
countnew = 0
countold = 0
**for u in js['users'] :**
friend = u['screen_name']
print friend
cur.execute('SELECT friends FROM Twitter WHERE name = ? |
LIMIT 1',
(friend, ) )
**try:**
count = cur.fetchone()[0]
cur.execute('UPDATE Twitter SET friends = ? |
WHERE name = ?',
(count+1, friend) )
countold = countold + 1
**except:**
cur.execute('''INSERT INTO Twitter (name, retrieved, friends)
VALUES ( ?, 0, 1 )''', ( friend, ) )
countnew = countnew + 1
print 'New accounts=',countnew,' revisited=',countold
conn.commit()
Once the cursor executes the SELECT statement, we mus... |
We
could do this with a for statement, but since we are only retrieving one row (LIMIT
1), we can use the fetchone() method to fetch the first (and only) row that is the
result of the SELECT operation. |
Since fetchone() returns the row as a tuple (even
though there is only one field), we take the first value from the tuple using to get
the current friend count into the variable count.
If this retrieval is successful, we use the SQL UPDATE statement with a WHERE clause
to add 1 to the friends column for the row that m... |
clause on the SELECT statement. |
So in the except block, we
use the SQL INSERT statement to add the friend’s screen_name to the table with
an indication that we have not yet retrieved the screen_name and set the friend
count to zero.
So the first time the program runs and we enter a Twitter account, the program
runs as follows:
Enter a Twitter accou... |
Then we retrieve some friends and add them all to the database
since the database is empty.
At this point, we might want to write a simple database dumper to take a look at
what is in our spider.sqlite3 file:
import sqlite3
conn = sqlite3.connect('spider.sqlite')
cur = conn.cursor()
cur.execute('SELECT * FROM Twitte... |
We can run the program again and tell it to retrieve the friends of the
next “unprocessed” account by simply pressing enter instead of a Twitter account
as follows:
Enter a Twitter account, or quit:
Retrieving http://api.twitter.com/1.1/friends ...
New accounts= 18 revisited= 2
Enter a Twitter account, or quit:
----... |
We also use the
fetchone()[0] pattern within a try/except block to either extract a screen_name
from the retrieved data or put out an error message and loop back up.
If we successfully retrieved an unprocessed screen_name, we retrieve their data as
follows:
~~ {.python{ url = twurl.augment(TWITTER_URL, {‘screen_name’... |
This keeps us from retrieving the same data over and over
and keeps us progressing forward through the network of Twitter friends.
If we run the friend program and press enter twice to retrieve the next unvisited
friend’s friends, then run the dumping program, it will give us the following output:
('opencontent', 1, ... |
Also the accounts cnxorg and kthanos already have two followers.
Since we now have retrieved the friends of three people (drchuck, opencontent,
and lhawthorn) our table has 55 rows of friends to retrieve.
-----
Each time we run the program and press enter it will pick the next unvisited
account (e.g., the next accou... |
The act of deciding how to break up your application
data into multiple tables and establishing the relationships between the tables
is called data modeling. |
The design document that shows the tables and their
relationships is called a data model.
Data modeling is a relatively sophisticated skill and we will only introduce the
most basic concepts of relational data modeling in this section. |
For more detail on
data modeling you can start with:
[http://en.wikipedia.org/wiki/Relational_model](http://en.wikipedia.org/wiki/Relational_model)
Let’s say for our Twitter spider application, instead of just counting a person’s
friends, we wanted to keep a list of all of the incoming relationships so we could
find ... |
So we create a new table that
keeps track of pairs of friends. |
The following is a simple way of making such a
table:
**CREATE TABLE Pals (from_friend TEXT, to_friend TEXT)**
Each time we encounter a person who drchuck is following, we would insert a row
of the form:
**INSERT INTO Pals (from_friend,to_friend) VALUES ('drchuck', 'lhawthorn')**
As we are processing the 20 friends... |
If we need the data more than once, we create a
numeric key for the data and reference the actual data using this key.
In practical terms, a string takes up a lot more space than an integer on the disk
and in the memory of our computer, and takes more processor time to compare
and sort. |
If we only have a few hundred entries, the storage and processor time
hardly matters. |
But if we have a million people in our database and a possibility
-----
of 100 million friend links, it is important to be able to scan data as quickly as
possible.
We will store our Twitter accounts in a table named People instead of the Twitter
table used in the previous example. |
The People table has an additional column
to store the numeric key associated with the row for this Twitter user. |
SQLite has
a feature that automatically adds the key value for any row we insert into a table
using a special type of data column (INTEGER PRIMARY KEY).
We can create the People table with this additional id column as follows:
**CREATE TABLE People**
(id INTEGER PRIMARY KEY, name TEXT UNIQUE, retrieved INTEGER)
Noti... |
When we select INTEGER PRIMARY KEY as the type of our id column, we are
indicating that we would like SQLite to manage this column and assign a unique
numeric key to each row we insert automatically. |
We also add the keyword UNIQUE
to indicate that we will not allow SQLite to insert two rows with the same value
for name.
Now instead of creating the table Pals above, we create a table called Follows
with two integer columns from_id and to_id and a constraint on the table that the
_combination of from_id and to_id mu... |
The rules both keep us from making mistakes and make it simpler to
write some of our code.
In essence, in creating this Follows table, we are modelling a “relationship” where
one person “follows” someone else and representing it with a pair of numbers indicating that (a) the people are connected and (b) the direction ... |
Here is the code for the new version of
the program:
import urllib.request, urllib.parse, urllib.error
import twurl
import json
import sqlite3
-----
Figure 15.4: Relationships Between Tables
TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json'
conn = sqlite3.connect('friends.sqlite')
cur = conn.cursor()
... |
LIMIT 1',
(acct, ))
**try:**
id = cur.fetchone()[0]
**except:**
cur.execute('''INSERT OR IGNORE INTO People
(name, retrieved) VALUES (?, 0)''', (acct, ))
-----
conn.commit()
**if cur.rowcount != 1:**
print('Error inserting account:', acct)
**continue**
id = cur.lastrowid
url = twurl.augment(TWITTER_URL, {'scre... |
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
countn... |
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: (1) look up the person in the People
table and retrieve the id value for the person or (2) add the person to the
People table and... |
Insert the row that captures the “follows” relationship.
We will cover each of these in turn.
###### 15.8.1 Constraints in database tables
As we design our table structures, we can tell the database system that we would
like it to enforce a few rules on us. |
These rules help us from making mistakes and
introducing incorrect data into out tables. |
When we create our 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))''')
We indicate that the name column in the People table must be UNIQ... |
We also
indicate that the combination of the two numbers in each row of the Follows table
must be unique. |
These constraints keep us from making mistakes such as adding
the same relationship more than once.
We can take advantage of these constraints in the following code:
cur.execute('''INSERT OR IGNORE INTO People (name, retrieved)
VALUES ( ?, 0)''', ( friend, ) )
We add the OR IGNORE clause to our INSERT statement to i... |
We are using the database constraint as a safety net to make sure we don’t inadvertently do something incorrect.
Similarly, the following code ensures that we don’t add the exact same Follows
relationship twice.
cur.execute('''INSERT OR IGNORE INTO Follows
(from_id, to_id) VALUES (?, ?)''', (id, friend_id) )
Again, ... |
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.
This is a very common pattern and is done twice in the program above. |
This code
shows how we look up the id for a friend’s account when we have extracted a
screen_name from a user node in the retrieved Twitter JSON.
Since over time it will be increasingly likely that the account will already be in
the database, we first check to see if the People record exists using a SELECT
statement.
... |
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
cou... |
We use INSERT OR IGNORE just to avoid errors and then
call commit() to force the database to really be updated. |
After the write is done,
we can check the cur.rowcount to see how many rows were affected. |
Since we are
attempting to insert a single row, if the number of affected rows is something other
than 1, it is an error.
If the INSERT is successful, we can look at cur.lastrowid to find out what value
the database assigned to the id column in our newly created row.
###### 15.8.3 Storing the friend relationship
Onc... |
In the People
table, we can see that the first three people have been visited and their data has
been retrieved. |
The data in the Follows table indicates that drchuck (user 1) is
a friend to all of the people shown in the first five rows. |
This makes sense because
the first data we retrieved and stored was the Twitter friends of drchuck. |
If you
were to print more rows from the Follows table, you would see the friends of users
2 and 3 as well.
-----
##### 15.9 Three kinds of keys
Now that we have started building a data model putting our data into multiple
linked tables and linking the rows in those tables using keys, we need to look at
some termino... |
There are generally three kinds of keys used in a
database model.
- A logical key is a key that the “real world” might use to look up a row. |
In
our example data model, the name field is a logical key. It is the screen name
for the user and we indeed look up a user’s row several times in the program
using the name field. |
You will often find that it makes sense to add a UNIQUE
constraint to a logical key. |
Since the logical key is how we look up a row
from the outside world, it makes little sense to allow multiple rows with the
same value in the table.
- A primary key is usually a number that is assigned automatically by the
database. |
It generally has no meaning outside the program and is only used
to link rows from different tables together. |
When we want to look up a row
in a table, usually searching for the row using the primary key is the fastest
way to find the row. |
Since primary keys are integer numbers, they take up
very little storage and can be compared or sorted very quickly. |
In our data
model, the id field is an example of a primary key.
- A foreign key is usually a number that points to the primary key of an
associated row in a different table. |
An example of a foreign key in our data
model is the from_id.
We are using a naming convention of always calling the primary key field name id
and appending the suffix _id to any field name that is a foreign key.
##### 15.10 Using JOIN to retrieve data
Now that we have followed the rules of database normalization an... |
In the JOIN clause you specify
the fields that are used to reconnect the rows between the tables.
The following is an example of a SELECT with a JOIN clause:
**SELECT * FROM Follows JOIN People**
**ON Follows.from_id = People.id WHERE People.id = 1**
The JOIN clause indicates that the fields we are selecting cross ... |
The ON clause indicates how the two tables are to be joined:
Take the rows from Follows and append the row from People where the field
from_id in Follows is the same the id value in the People table.
The result of the JOIN is to create extra-long “metarows” which have both the
fields from People and the matching field... |
Where there is more
-----
|People|Follows|
|---|---|
|id name retrieved|from_id to_id 1 2 1 3 1 4 ...|
|1 drchuck 1 2 opencontent 1 3 lhawthorn 1 4 steve_coppin 0 ...||
|name|id|from_id|to_id name|
|---|---|---|---|
|drchuck drchuck drchuck|1 1 1 1 1 1||2 opencontent 3 lhawthorn 4 steve_coppin|
Figure 15.5: Conen... |
You
can also see that the second column (Follows.to_id) matches the third column
(People.id) in each of the joined-up “metarows”.
-----
##### 15.11 Summary
This chapter has covered a lot of ground to give you an overview of the basics of
using a database in Python. |
It is more complicated to write the code to use a
database to store data than Python dictionaries or flat files so there is little reason
to use a database unless your application truly needs the capabilities of a database.
The situations where a database can be quite useful are: (1) when your application
needs to make... |
When you start making links between tables, it is important to
do some thoughtful design and follow the rules of database normalization to make
the best use of the database’s capabilities. |
Since the primary motivation for using
a database is that you have a large amount of data to deal with, it is important to
model your data efficiently so your programs run as fast as possible.
##### 15.12 Debugging
One common pattern when you are developing a Python program to connect to
an SQLite database will be to... |
The browser allows you to quickly check to see
if your program is working properly.
You must be careful because SQLite takes care to keep two programs from changing
the same data at the same time. |
For example, if you open a database in the browser
and make a change to the database and have not yet pressed the “save” button
in the browser, the browser “locks” the database file and keeps any other program
from accessing the file. |
In particular, your Python program will not be able to
access the file if it is locked.
So a solution is to make sure to either close the database browser or use the
_File menu to close the database in the browser before you attempt to access the_
database from Python to avoid the problem of your Python code failing b... |
More commonly called a “column” or**
“field”.
**constraint When we tell the database to enforce a rule on a field or a row in a**
table. |
A common constraint is to insist that there can be no duplicate values
in a particular field (i.e., all the values must be unique).
-----
**cursor A cursor allows you to execute SQL commands in a database and retrieve**
data from the database. |
A cursor is similar to a socket or file handle for
network connections and files, respectively.
**database browser A piece of software that allows you to directly connect to a**
database and manipulate the database directly without writing a program.
**foreign key A numeric key that points to the primary key of a row... |
Foreign keys establish relationships between rows stored in different
tables.
**index Additional data that the database software maintains as rows and inserts**
into a table to make lookups very fast.
**logical key A key that the “outside world” uses to look up a particular row. |
For**
example in a table of user accounts, a person’s email address might be a good
candidate as the logical key for the user’s data.
**normalization Designing a data model so that no data is replicated. |
We store**
each item of data at one place in the database and reference it elsewhere
using a foreign key.
**primary key A numeric key assigned to each row that is used to refer to one row**
in a table from another table. |
Often the database is configured to automatically assign primary keys as rows are inserted.
**relation An area within a database that contains tuples and attributes. |
More**
typically called a “table”.
**tuple A single entry in a database table that is a set of attributes. |
More typically**
called “row”.
-----
-----
## Chapter 16
# Visualizing data
So far we have been learning the Python language and then learning how to use
Python, the network, and databases to manipulate data.
In this chapter, we take a look at three complete applications that bring all of these
things together t... |
You might use these applications as
sample code to help get you started in solving a real-world problem.
Each of the applications is a ZIP file that you can download and extract onto your
computer and execute.
##### 16.1 Building a Google map from geocoded data
In this project, we are using the Google geocoding API ... |
If you have a lot of data, you might need to
stop and restart the lookup process several times. |
So we break the problem into
two phases.
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. |
Before we use the geocoding API for each user-entered
location, we simply check to see if we already have the data for that particular line
of input. |
The database is functioning as a local “cache” of our geocoding data to
make sure we never ask Google for the same data twice.
You can restart the process at any time by removing the file geodata.sqlite.
Run the geoload.py program. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.