Saving data in SQL databases

Source: Internet
Author: User

Saving data to a database is ideal for repeating or structured data, such as contact information. this class assumes that you are familiar with SQL databases in general and helps you get started with SQLite databases on Android. the APIS you'll need to use
A database on Android are available inandroid.database.sqlitePackage.

Define a schema and contract

One of the main principles of SQL databases is the schema: a formal declaration of how the database is organized. the schema is reflected in the SQL statements that you use to create your database. you may find it helpful to create a companion class, known
AsContractClass, which explicitly specifies the layout of your schema in a systematic and self-documenting way.

A contract class is a container for constants that define names for Uris, tables, and columns. the contract class allows you to use the same constants internal SS all the other classes in the same package. this lets you change a column name in one place and have
It propagate throughout your code.

A good way to organize a contract class is to put definitions that are global to your whole database in the root level of the class. then create an inner class for each table that enumerates its columns.

Note:By implementingBaseColumnsInterface, your inner class can inherit a primary key field called
_IDThat some Android classes such as cursor adaptors will perform CT it to have. It's not required, but this can help your database work harmoniously with the android framework.

For example, this snippet defines the table name and column names for a single table:

public static abstract class FeedEntry implements BaseColumns {    public static final String TABLE_NAME = "entry";    public static final String COLUMN_NAME_ENTRY_ID = "entryid";    public static final String COLUMN_NAME_TITLE = "title";    public static final String COLUMN_NAME_SUBTITLE = "subtitle";    ...}

To prevent someone from accidentally instantiating the contract class, give it an empty constructor.

// Prevents the FeedReaderContract class from being instantiated.private FeedReaderContract() {}
Create a database using a SQL helper

Once you have defined how your database looks, you shocould implement methods that create and maintain the database and tables. Here are some typical statements that create and delete a table:

private static final String TEXT_TYPE = " TEXT";private static final String COMMA_SEP = ",";private static final String SQL_CREATE_ENTRIES =    "CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + " (" +    FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY," +    FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +    FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +    ... // Any other options for the CREATE command    " )";private static final String SQL_DELETE_ENTRIES =    "DROP TABLE IF EXISTS " + TABLE_NAME_ENTRIES;

Just like files that you save on the device's internal storage, Android stores your database in private disk space that's associated application. your data is secure, because by default this area is not accessible to other applications.

A useful set of APIS is available inSQLiteOpenHelperClass. When you use this class to obtain references to your database, the system performs the potentially long-running operations of creating and updating the database
Only when needed andNot during app startup. All you need to do is call
getWritableDatabase()OrgetReadableDatabase().

Note:Because they can be long-running, be sure that you call
getWritableDatabase()OrgetReadableDatabase()In a background thread, such as
AsyncTaskOrIntentService.

To useSQLiteOpenHelper, Create a subclass that overrides
onCreate(),onUpgrade()And
onOpen()Callback methods. You may also want to implement
onDowngrade(), But it's not required.

For example, here's an implementationSQLiteOpenHelperThat uses some of the commands shown above:

public class FeedReaderDbHelper extends SQLiteOpenHelper {    // If you change the database schema, you must increment the database version.    public static final int DATABASE_VERSION = 1;    public static final String DATABASE_NAME = "FeedReader.db";    public FeedReaderDbHelper(Context context) {        super(context, DATABASE_NAME, null, DATABASE_VERSION);    }    public void onCreate(SQLiteDatabase db) {        db.execSQL(SQL_CREATE_ENTRIES);    }    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        // This database is only a cache for online data, so its upgrade policy is        // to simply to discard the data and start over        db.execSQL(SQL_DELETE_ENTRIES);        onCreate(db);    }    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {        onUpgrade(db, oldVersion, newVersion);    }}

To access your database, instantiate your subclassSQLiteOpenHelper:

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());
Put information into a database

Insert data into the database by passingContentValuesObject to
insert()Method:

// Gets the data repository in write modeSQLiteDatabase db = mDbHelper.getWritableDatabase();// Create a new map of values, where column names are the keysContentValues values = new ContentValues();values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID, id);values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT, content);// Insert the new row, returning the primary key value of the new rowlong newRowId;newRowId = db.insert(         FeedReaderContract.FeedEntry.TABLE_NAME,         FeedReaderContract.FeedEntry.COLUMN_NAME_NULLABLE,         values);

The first argumentinsert()Is simply the table name. The second argument provides the name of a column in which the framework can insert null in the event that
ContentValuesIs empty (if you instead set this
"null"
, Then the framework will not insert a row when there are no values ).

Read information from a database

To read from a database, usequery()Method, passing it your selection criteria and desired columns. The method combines elements
insert()Andupdate(), Could t the column list defines the data you want to fetch, rather than the data to insert. The results of the query are returned to you in
CursorObject.

SQLiteDatabase db = mDbHelper.getReadableDatabase();// Define a projection that specifies which columns from the database// you will actually use after this query.String[] projection = {    FeedReaderContract.FeedEntry._ID,    FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,    FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED,    ...    };// How you want the results sorted in the resulting CursorString sortOrder =    FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED + " DESC";Cursor c = db.query(    FeedReaderContract.FeedEntry.TABLE_NAME,  // The table to query    projection,                               // The columns to return    selection,                                // The columns for the WHERE clause    selectionArgs,                            // The values for the WHERE clause    null,                                     // don't group the rows    null,                                     // don't filter by row groups    sortOrder                                 // The sort order    );

To look at a row in the cursor, use one ofCursorMove methods, which you must always call before you begin reading values. Generally, you shoshould start by calling
moveToFirst(), Which places the "read position" on the first entry in the results. For each row, you can read a column's value by calling one of
CursorGet methods, suchgetString()Or
getLong(). For each of the get methods, you must pass the index position of the column you desire, which you can get by calling
getColumnIndex()OrgetColumnIndexOrThrow(). For example:

cursor.moveToFirst();long itemId = cursor.getLong(    cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry._ID));
Delete information from a database

To delete rows from a table, you need to provide selection criteria that identify the rows. the database API provides a mechanism for creating selection criteria that protects against SQL injection. the mechanic divides the selection specification
A selection clause and selection arguments. the clause defines the columns to look at, and also allows you to combine column tests. the arguments are values to test against that are bound into the clause. because the result isn' t handled the same as a regular
SQL statement, it is immune to SQL injection.

// Define 'where' part of query.String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";// Specify arguments in placeholder order.String[] selelectionArgs = { String.valueOf(rowId) };// Issue SQL statement.db.delete(table_name, mySelection, selectionArgs);
Update a database

When you need to modify a subset of your database values, useupdate()Method.

Updating the table combines the content values Syntaxinsert()With
whereSyntaxdelete().

SQLiteDatabase db = mDbHelper.getReadableDatabase();// New value for one columnContentValues values = new ContentValues();values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);// Which row to update, based on the IDString selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";String[] selelectionArgs = { String.valueOf(rowId) };int count = db.update(    FeedReaderDbHelper.FeedEntry.TABLE_NAME,    values,    selection,    selectionArgs);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.