[关闭]
@kimo 2016-01-08T08:07:26.000000Z 字数 4939 阅读 1763

Saving Data in SQL Databases

android



Define a Schema and Contract


  1. public final class FeedReaderContract {
  2. // To prevent someone from accidentally instantiating the contract class,
  3. // give it an empty constructor.
  4. public FeedReaderContract() {}
  5. /* Inner class that defines the table contents */
  6. public static abstract class FeedEntry implements BaseColumns {
  7. public static final String TABLE_NAME = "entry";
  8. public static final String COLUMN_NAME_ENTRY_ID = "entryid";
  9. public static final String COLUMN_NAME_TITLE = "title";
  10. public static final String COLUMN_NAME_SUBTITLE = "subtitle";
  11. ...
  12. }
  13. }

Create a Database Using a SQL Helper


For example, here's an implementation of SQLiteOpenHelper

  1. public class FeedReaderDbHelper extends SQLiteOpenHelper {
  2. private static final String TEXT_TYPE = " TEXT";
  3. private static final String COMMA_SEP = ",";
  4. private static final String SQL_CREATE_ENTRIES =
  5. "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
  6. FeedEntry._ID + " INTEGER PRIMARY KEY," +
  7. FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
  8. FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
  9. ... // Any other options for the CREATE command
  10. " )";
  11. private static final String SQL_DELETE_ENTRIES =
  12. "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
  13. // If you change the database schema, you must increment the database version.
  14. public static final int DATABASE_VERSION = 1;
  15. public static final String DATABASE_NAME = "FeedReader.db";
  16. public FeedReaderDbHelper(Context context) {
  17. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  18. }
  19. public void onCreate(SQLiteDatabase db) {
  20. db.execSQL(SQL_CREATE_ENTRIES);
  21. }
  22. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  23. // This database is only a cache for online data, so its upgrade policy is
  24. // to simply to discard the data and start over
  25. db.execSQL(SQL_DELETE_ENTRIES);
  26. onCreate(db);
  27. }
  28. public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  29. onUpgrade(db, oldVersion, newVersion);
  30. }
  31. }

To access your database, instantiate your subclass of SQLiteOpenHelper:

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());

Put Information into a Database

Insert data into the database by passing a ContentValues object to the insert() method:

  1. // Gets the data repository in write mode
  2. SQLiteDatabase db = mDbHelper.getWritableDatabase();
  3. // Create a new map of values, where column names are the keys
  4. ContentValues values = new ContentValues();
  5. values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
  6. values.put(FeedEntry.COLUMN_NAME_TITLE, title);
  7. values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
  8. // Insert the new row, returning the primary key value of the new row
  9. long newRowId;
  10. newRowId = db.insert(
  11. FeedEntry.TABLE_NAME,
  12. FeedEntry.COLUMN_NAME_NULLABLE,
  13. values);

The first argument for insert() 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 the ContentValues is empty (if you instead set this to "null", then the framework will not insert a row when there are no values).


Read Information from a Database

  1. SQLiteDatabase db = mDbHelper.getReadableDatabase();
  2. // Define a projection that specifies which columns from the database
  3. // you will actually use after this query.
  4. String[] projection = {
  5. FeedEntry._ID,
  6. FeedEntry.COLUMN_NAME_TITLE,
  7. FeedEntry.COLUMN_NAME_UPDATED,
  8. ...
  9. };
  10. // How you want the results sorted in the resulting Cursor
  11. String sortOrder =
  12. FeedEntry.COLUMN_NAME_UPDATED + " DESC";
  13. Cursor c = db.query(
  14. FeedEntry.TABLE_NAME, // The table to query
  15. projection, // The columns to return
  16. selection, // The columns for the WHERE clause
  17. selectionArgs, // The values for the WHERE clause
  18. null, // don't group the rows
  19. null, // don't filter by row groups
  20. sortOrder // The sort order
  21. );

To look at a row in the cursor, use one of the Cursor move methods, which you must always call before you begin reading values. Generally, you should 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 the Cursor get methods, such as getString() or getLong(). For each of the get methods, you must pass the index position of the column you desire, which you can get by callinggetColumnIndex() or getColumnIndexOrThrow(). For example:

cursor.moveToFirst();
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedEntry._ID)
);

Delete Information from a Database


  1. // Define 'where' part of query.
  2. String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
  3. // Specify arguments in placeholder order.
  4. String[] selectionArgs = { String.valueOf(rowId) };
  5. // Issue SQL statement.
  6. db.delete(table_name, selection, selectionArgs);

Update a Database


  1. SQLiteDatabase db = mDbHelper.getReadableDatabase();
  2. // New value for one column
  3. ContentValues values = new ContentValues();
  4. values.put(FeedEntry.COLUMN_NAME_TITLE, title);
  5. // Which row to update, based on the ID
  6. String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
  7. String[] selectionArgs = { String.valueOf(rowId) };
  8. int count = db.update(
  9. FeedReaderDbHelper.FeedEntry.TABLE_NAME,
  10. values,
  11. selection,
  12. selectionArgs);
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注