By default all databases are private, accessible only by the application that created them
SQLite is a well regarded relational database management system (RDBMS).
SQLite differs from many conventional database engines by loosely typing each column, meaning that column values are not required to conform to a single type
https://github.com/coderetriever/Android/tree/master/Databases
Introducing the SQLiteOpenHelper
SQLiteOpenHelper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases
The onCreate() method creates a new database if the required database is not present.
The onUpgrade() method is called when the database needs to be upgraded.
private static class myDbHelper extends SQLiteOpenHelper {
public myDbHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs to create a new one.
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +
_oldVersion + " to " +
_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple previous versions can be handled by comparing _oldVersion and _newVersion values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Create a new one.
onCreate(_db);
}
}
}
dbHelper = new myDbHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase db;
try {
db = dbHelper.getWritableDatabase();
}
catch (SQLiteException ex){
db = dbHelper.getReadableDatabase();
}
Opening and Creating Databases without SQLiteHelper
Setting up a database is a two-step process
- First call openOrCreateDatabase to create the new database
- Then call execSQL on the resulting database instance to run the SQL commands that will create your tables and their relationships
private static final String DATABASE_NAME = "myDatabase.db";
private static final String DATABASE_TABLE = "mainTable";
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " ( _id integer primary key autoincrement,"
+ "column_one text not null);";
SQLiteDatabase myDatabase;
private void createDatabase() {
myDatabase = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE,
null);
myDatabase.execSQL(DATABASE_CREATE);
}
Querying a Database
Each database query is returned as a Cursor. Think of the Cursor as a pointer to the result set from a database query
To execute a query on a database use the query method
- should contain only unique values?
- The name of the table to query
- lists the columns to include in the result set
- A ‘‘where’’ clause that defines the rows to be returned. can include ? wildcards that will be replaced by the values passed in through the selection argument parameter
- An array of selection argument strings that will replace the ?’s in the where clause
- A ‘‘group by’’ clause that defines how the resulting rows will be grouped
- A ‘‘having’’ filter that defines which row groups to include if you specified a group by clause
- A string that describes the order of the returned rows
- An optional string that defines a limit for the number of returned rows
// Return all rows for columns one and three, no duplicates
String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3};
Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns,
null, null, null, null, null, null);
// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where,
null, null, null, order)
Cursors are pointers to the result set within the underlying data. Cursor class includes a number of navigation functions.
moveToFirst
moveToNext
moveToPrevious
getCount
getColumnIndexOrThrow
getColumnName
getColumnNames
moveToPosition
getPosition
The startManagingCursor method integrates the Cursor’s lifetime into the calling Activity’s. When you’ve finished with the Cursor, call stopManagingCursor to do just that.
Then use the type safe get<type> methods (passing in a column index) to return the value
String columnValue = myResult.getString(columnIndex);
int GOLD_HOARDED_COLUMN = 2;
Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);
float totalHoard = 0f;
// Make sure there is at least one row.
if (myGold.moveToFirst()) {
// Iterate over each cursor.
do {
float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);
totalHoard += hoard;
} while(myGold.moveToNext());
}
float averageHoard = totalHoard / myGold.getCount();
Content Values
ContentValues are used to insert new rows into tables.
Its put() method enables you to insert keys with values of different data types.
Adding, Updating, and Removing Rows
The SQLiteDatabase class exposes insert, delete, and update methods that encapsulate the SQL statements required to perform these actions
The execSQL method lets you execute any valid SQL on your database tables
Any time you modify the underlying database values, you should call refreshQuery on each Cursor that has a view on the affected table
Inserting New Rows
// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
// Insert the row into your table
myDatabase.insert(DATABASE_TABLE, null, newValues);
Updating a Row
Call update on the database, passing in the table name, the updated Content Values object, and a where clause that specifies the row(s) to update
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
String where = KEY_ID + "=" + rowId;
// Update the row with the specified index with the new values.
myDatabase.update(DATABASE_TABLE, newValues, where, null);
Deleting Rows
specifying the table name and a where clause
myDatabase.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null);
Upgrading the Database
Sometimes, after creating and using the database, you may need to add additional tables, change
the schema of the database, or add columns to your tables. In this case, you need to migrate your
existing data from the old database to a newer one
To upgrade the database, change the DATABASE_VERSION constant to a value higher than the
previous one.
static final int DATABASE_VERSION = 2;
Pre-Creating the Database
In real-life applications, sometimes it would be more effi cient to pre-create the database at design
time rather than runtime.
To pre-create a SQLite database, you can use SQLite Database Browser
With the database created at design time, the next thing you should do is bundle it together with
your application so that you can use it in your application
NOTE Note that a filename for files added to the assets folder must be in
lowercase letters. As such, a filename such as MyDB is invalid, whereas mydb is fine.
When the activity is created, you copy the database fi le located in the assets folder into the /data/
data/net.learn2develop.Databases/databases/ folder on the Android device
You copy the database fi le only if it does not exist in the destination folder
No comments:
Post a Comment