Advanced Android Development: Lesson 6.01 - Working With SQL and Sqlite
Advanced Android Development: Lesson 6.01 - Working With SQL and Sqlite
DEVELOPMENT
Lesson 6.01 Working with SQL and SQLite
SQLite
It is typical for applications to store data in a relational database. A database is very efficient at
working with different types of data, and is able to quickly recall that data as it becomes necessary.
Android provides SQLite database engine for us to work with.
"SQLite is a software library that implements a self-contained, serverless, zero-configuration,
transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the
world. The source code for SQLite is in the public domain."
http://www.sqlite.org/
Databases
Before we get down to the details about how SQLite actually works, lets take a step back, and look at
databases in general.
A database is really nothing more than a well organized storage facility for your data. Everyone, at
one time or another, or on a regular basis, uses databases, and may not even know it.
For example, Google search engine, is a large database of web sites. Your address book maintained
by your email program, is a database. A checkbook manager that helps you balance your finances,
is a database. And even the television schedule that you retrieve on your DVR or cable box is a
database.
Database
Think of a database as a file cabinet.
A well organized file cabinet will have sections for different types of files. For example, you may have
a set of files about your authors in the top drawer. A set of files about the books they wrote in the
middle drawer, and a set of publishers who published those books for those authors in the third drawer.
The problem with the file cabinet though is that its not easy to quickly identify all of the books that
were written in a specific year, or identify all of the publishers used by a particular author. For that
matter, you'd have to do some digging in order to find all of the books that an author wrote
throughout his or her career. These are typicaly queries that are easily addressed with a well
managed database.
Relationships
The easiest way to describe the relationship between Authors, Titles, and Publishers is with the above
database "schema". A schema is a database diagram, or representation.
In the Authors table, we are storing the name and year of birth for the author. Each author is assigned
a unique identifier called Au_ID. That identifier is used in in the Title Authors table to associate one or
more book ISBN numbers to an author in my Authors table. The ISBN is also a unique identifier, and
joins to the Titles table, where each book is described. Finally, the Publishers table joins to the Titles
table in order to establish the relationship between the publisher and the books they released to
market.
Primary Keys
Those unique identifiers I mentioned before, are known as primary keys. They are always unique. Even
if a record is deleted from a database, the deleted primary key will never be introduced back into the
database naturally. You can certainly, re-create the deleted record manually.
The primary keys, and the relationships defined between tables, help keep data integrity, consistency,
and makes it easily searchable. Deleting an author would require you to also delete all of the books
that the author wrote (unless co-authored), as an example.
Table
Fields
Designing a Schema
The first step, when building your new database, is to review and organize your data into categories.
While reviewing your data, look for ways to minimize data redundancy. Duplicate data in multiple
tables is wasteful, and is difficult to maintain. The art of removing duplicate information and replacing
it with a relationship instead is known as normalization.
Table Relationships
There are several different types of relationships that can be set up between database tables.
A relationship represents how a table is able to locate related information in another table within your
database. The basic relationships are:
One To One This means that one record in Table A has one record of related information available
in Table B.
One To Many Table A has one record, but Table B has multiple records that relate the record in A.
Many To Many Multiple records in Table A can relate to multiple records in Table B.
Alternatively, data can stand on its own, and it isnt always necessary for a table to have a
relationship with another table.
This classification of the number of records that can exist on each side of the relationship is known as
the "Cardinality".
Table A
Customer #
Name
12345 Test Person
12346 Another Person
12347 Last Person
Table B
Credit ID
7
8
9
Customer #
Credit Limit
12345
$500
12346
$1,000
12347 $
500.00
Address
123 Main Street
44 Main Street
55 Main Street
Phone
555-1212
555-1111
555-1010
Table A
Customer #
Name
12345 Test Person
12346 Another Person
12347 Last Person
Address
123 Main Street
44 Main Street
55 Main Street
Phone
555-1212
555-1111
555-1010
Table B
Invoice #
3
4
5
Customer #
12345
12345
12347
Amount
$299
$199
$399
Customer #
12345
12346
12347
12345
12347
Address
123 Main Street
44 Main Street
55 Main Street
Phone
555-1212
555-1111
555-1010
Credit Card ID
1
3
2
2
3
Credit Card ID
Type
1 Visa
2 Mastercard
3 American Express
Joins
There are several different ways of joining tables together using SQLite T-SQL queries.
Inner Join allows you to select records from two or more tables where ONLY the matching records
are returned. So if you have a Customer and Invoice table, and there are more customers than
invoices, only records for customers who have invoices will be returned.
Outer Join An outer join allows you to look at data in both tables. An outer join will return records
that match, but also return records from the table you joined to that do not match. So, again, with
Customers and Invoices, an outer join would return everything that the Inner join did, but in addition
to that it would return the remaining customers, with no information for the invoice portion of your
result set.
As we build tables, and views, joins and their usage will become more apparent.
Database Managers
There are a number of free, and paid applications that can be used to manage your SQLite
database.
NaviCat - http://www.navicat.com/ - This is a premium database management tool, which supports
many different databases, not just SQLite. I use it with MySQL, SQLite, and SQL Server. Windows
only.
SQLite Admin - http://sqliteadmin.orbmu2k.de/ - This is a Windows only utility. Free.
SQLite Manager - http://www.sqlabs.com/sqlitemanager.php - Windows and OS X friendly, but not
free.
SQLite Manager https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/ - This is a free
Firefox add-on. It works across Windows, OS X, and Linux, and the utility we'll be using in this class.
Getting Started
Using Firefox, download and install the SQLite Manager v0.77 (or higher).
After the installation, the tool will become available in your Firefox menu, under Web Developer.
SQLite Manager
Once you open SQLite Manager, you can close Firefox.
To create a new database, select Database, then New Database. Give it a path and filename.
Building Tables
Once you have a database created, you can add tables. To do so, right-click over the Tables node,
and select Create Table. You can also use the Create Table icon in the SQLite Manager toolbar.
true).
Columns
Column Names Column names should not have spaces in them, if you can avoid it.
2. Data Type These are the external data types for
your defined fields.
3. Options
Primary Key Set this if the field you are working
2
3
1
with is the unique identifier for each record.
Autoinc? Auto-incremental integer option.
This is often used with Primary Keys, which start
at 1 and increment automatically each time
a new record is added.
Allow Null? If checked, empty, or null values
can be stored in the field, otherwise a value
must be provided.
Unique? Creates a field who's value must be
unique. A primary key is a unique value.
Default Value We can specify a default for
the database to use, when adding new records.
1.
Creating Data
1.
2.
3.
4.
2
1
Running Queries
1.
2.
3.
4.
2
3
Rules
Important things to know about SQL statements:
Tables and fields that contain spaces, punctuations, or named after SQL keywords must be
Select
The select statement can be used to select data from a table or tables within a database.
Syntax:
SELECT Field1, Field2, Field3
FROM TableName
WHERE user specified condition exists
Examples:
SELECT * FROM Authors
SELECT Authors.Au_ID, Authors.Author, [Title Author].ISBN
FROM Authors INNER JOIN [Title Author] ON Authors.Au_ID = [Title Author].Au_ID
WHERE Authors.Au_ID = 7576
Aggregate Functions
There are a number of useful functions available within SQL to help aggregate data.
We can collect the Sum, Average, Min and Max data of specified fields. It is also possible to limit the
number of records returned by the query using the LIMIT keyword. Using DISTINCT, you can get a set of
unique records.
Examples:
SELECT SUM ([Year Born]) AS SumYear, AVG ([Year Born]) AS AvgBorn,
MAX([Year Born]) AS Youngest, MIN ([Year Born]) AS Oldest
FROM Authors
WHERE [Year Born] IS NOT NULL
Sort Order
You can specify a sort order for the results of your select queries. Sorting can be done on multiple
fields, and each field can be sorted in an ascending or descending fashion.
Examples:
SELECT * FROM Authors
WHERE [Year Born] BETWEEN 1940 AND 1970
ORDER BY Author, [Year Born] DESC
SELECT * FROM Authors
WHERE [Year Born] IS NOT 1970
ORDER BY Author DESC
Insert Statement
The INSERT statement allows us to add new records to a table. The syntax for the statement is as
follows:
INSERT INTO TableName (field1, field2, field3)
VALUES (value_for_field1, value_for_field2, value_for_field3)
The order in which you enter your field names should also be order in which you enter the values for
those fields. Because INSERT is an action query, it does not return any data.
Example:
INSERT INTO Authors
(Author, [Year Born])
VALUES ('Alex Tushinsky', 1970)
Notice that the query doesn't set a value for the AU_ID field. The correct primary key value will
automatically be added by the database when the record is inserted.
Update Statement
The UPDATE statement allows us to modify existing records. UPDATE is a very powerful statement that is
capable of altering an entire table, if not used correctly. Almost always, it requires the use of a WHERE
clause that specifically identifies the record you want to modify. Caution: If the WHERE clause is
omitted, the UPDATE statement will proceed to alter the entire table to the value specified by the
statement.
Syntax:
UPDATE TableName
SET Field1 = Value, Field2 = Value
WHERE RecordID = Value
Example:
UPDATE Authors
SET [Year Born] = 1970
WHERE Au_ID = 1
The above example will set the YEAR BORN field to 1970 on the record that has the Au_ID field set to 1.
If the WHERE clause was omitted, then the entire tables YEAR BORN field would be set to 1970.
Delete Statement
Finally, we can use the DELETE statement to remove records from a table. The DELETE statement works
very much like the SELECT statement with the exception that the records met by the search criteria will
be deleted rather than returned to the screen.
Syntax:
DELETE FROM TableName
WHERE RecordID = Value
Note that DELETE statements are generally performed on one table at a time. You do not specify
fields in a delete statement, as the entire record is removed. Caution: Once again, if you omit the
WHERE clause, SQL will proceed to delete every record in the table.
Examples:
DELETE FROM Authors
WHERE Au_ID = 1
DELETE FROM Authors
WHERE [Year Born] IS NOT NULL
DELETE FROM Authors