Retrieving Data
Now that our database has been created and populated, we can run queries to search for data that meets specified criteria. The general form of a query is as follows:
| SELECT ColumnName , ... FROM TableName |
The TableName is the name of the table to get the data from and the column names specify which columns to get values from. For example, this query retrieves all the data in the table PopByRegion:
| >>> cur.execute('SELECT Region, Population FROM PopByRegion') |
Once the database has executed this query for us, we can access the results one record at a time by calling the cursor’s fetchone method, just as we can read one line at a time from a file using readline:
| >>> cur.fetchone() |
| ('Central Africa', ... |
Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.