适用类型:重复、大量、结构化的数据

    在APP中,DB被保存到了程序的private空间,这些空间默认是私有的,不能被其它的应用所访问,从而保证了DB中数据的安全性

    在程序中,我们借助SQLiteOpenHelper对数据库进行读写操作,系统对于一些耗时的操作会在程序需要时才执行,而不是程序启动就开始执行,对于耗时的操作,我们应该AsyncTask or IntentService中进行,避免对程序主线程的影响

    1. package net.oschina.git.zhaikun.androiddeveloped.db;
    2. import android.content.Context;
    3. import android.database.sqlite.SQLiteDatabase;
    4. import android.database.sqlite.SQLiteOpenHelper;
    5. /**
    6. * Created by zhaikun68 on 2017/8/2.
    7. * <p>
    8. * SQLite数据操作类
    9. */
    10. public class SQLiteHelper extends SQLiteOpenHelper {
    11. private static final String TABLE_NAME = "students";//表名
    12. private static final String CREATE_TABLE_SQL =//创建表students
    13. "create table " + TABLE_NAME +
    14. "(" +
    15. "_id integer primary key," +//Android中SQLite默认的主键
    16. "id integer," +
    17. "name text" +
    18. //添加更多的属性
    19. ")";
    20. private static final String DELETE_TABLE_SQL =
    21. "DROP TABLE IF EXISTS " + TABLE_NAME;
    22. /**
    23. * Create a helper object to create, open, and/or manage a database.
    24. * This method always returns very quickly. The database is not actually
    25. * created or opened until one of {@link #getWritableDatabase} or
    26. * {@link #getReadableDatabase} is called.
    27. *
    28. * @param context to use to open or create the database
    29. * @param name of the database file, or null for an in-memory database
    30. * @param factory to use for creating cursor objects, or null for the default
    31. * @param version number of the database (starting at 1); if the database is older,
    32. * {@link #onUpgrade} will be used to upgrade the database; if the database is
    33. * newer, {@link #onDowngrade} will be used to downgrade the database
    34. */
    35. public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    36. super(context, name, factory, version);
    37. }
    38. /**
    39. * Called when the database is created for the first time. This is where the
    40. * creation of tables and the initial population of the tables should happen.
    41. *
    42. * @param db The database.
    43. */
    44. @Override
    45. public void onCreate(SQLiteDatabase db) {
    46. db.execSQL(CREATE_TABLE_SQL);
    47. }
    48. /**
    49. * Called when the database needs to be upgraded. The implementation
    50. * should use this method to drop tables, add tables, or do anything else it
    51. * needs to upgrade to the new schema version.
    52. * <p>
    53. * <p>
    54. * The SQLite ALTER TABLE documentation can be found
    55. * <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
    56. * you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
    57. * you can use ALTER TABLE to rename the old table, then create the new table and then
    58. * populate the new table with the contents of the old table.
    59. * </p><p>
    60. * This method executes within a transaction. If an exception is thrown, all changes
    61. * will automatically be rolled back.
    62. * </p>
    63. *
    64. * @param db The database.
    65. * @param oldVersion The old database version.
    66. * @param newVersion The new database version.
    67. */
    68. @Override
    69. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    70. db.execSQL(DELETE_TABLE_SQL);
    71. onCreate(db);
    72. }
    73. @Override
    74. public void onOpen(SQLiteDatabase db) {
    75. super.onOpen(db);
    76. }
    77. @Override
    78. public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    79. super.onDowngrade(db, oldVersion, newVersion);
    80. }
    81. }
    1. package net.oschina.git.zhaikun.androiddeveloped.activitys;
    2. import android.content.ContentValues;
    3. import android.database.Cursor;
    4. import android.database.sqlite.SQLiteDatabase;
    5. import android.os.Bundle;
    6. import android.support.annotation.Nullable;
    7. import android.support.v7.app.AppCompatActivity;
    8. import net.oschina.git.zhaikun.androiddeveloped.db.SQLiteHelper;
    9. /**
    10. * Created by zhaikun68 on 2017/8/2.
    11. * <p>
    12. * DB数据操作
    13. */
    14. public class DBActivity extends AppCompatActivity {
    15. private static final String DATABASE_NAME = "dbTest.db";//数据库名臣
    16. private static final int DATABASE_VERSION = 1;//数据库版本号
    17. private SQLiteHelper sqLiteHelper = new SQLiteHelper(this, DATABASE_NAME, null, DATABASE_VERSION);
    18. @Override
    19. protected void onCreate(@Nullable Bundle savedInstanceState) {
    20. super.onCreate(savedInstanceState);
    21. //1、向数据库写入数据
    22. SQLiteDatabase dbWrite = sqLiteHelper.getWritableDatabase();
    23. //向数据库中插入的列对应的值
    24. ContentValues contentValues = new ContentValues();
    25. contentValues.put("name", "123456");
    26. /**
    27. * insert()方法说明
    28. * 参数一:操作的表名
    29. * 参数二:参数会使得系统自动对那些ContentValues 没有提供数据的列填充数据为null,如果第二个参数传递的是null,那么系统则不会对那些没有提供数据的列进行填充
    30. */
    31. dbWrite.insert("students", null, contentValues);
    32. //2、读取数据库中的数据
    33. SQLiteDatabase dbRead = sqLiteHelper.getReadableDatabase();
    34. String[] columns = {"name"};
    35. String selection = "id=? and name=?";
    36. String[] selectionArgs = {"1", "小明"};//与selection中问号的先后顺序相对应,一个问号对应一个值
    37. /**
    38. * query()方法说明
    39. * 参数一:操作的表名
    40. * 参数二:查询的列的名称,返回所查询列对应的结果
    41. * 参数三:查询条件中的列
    42. * 参数四:查询条件中的列对应的值
    43. * 参数五:分组
    44. * 参数六:分组过滤
    45. * 参数七:排序
    46. * 返回Cursor游标对象
    47. */
    48. Cursor cursor = dbRead.query("students", columns, selection, selectionArgs, null, null, null);
    49. cursor.moveToFirst();//取游标中的数据,将读取位置移动到数据集中最开始的位置,使用cursor的其中一个get方法如getString()或getLong()获取列的值
    50. String name = cursor.getString(cursor.getColumnIndex("name"));//对于每一个get方法必须传递想要获取的列的索引位置,索引位置可以通过调用getColumnIndex()或getColumnIndexOrThrow()获得
    51. while (cursor.moveToNext()) {
    52. name = cursor.getString(cursor.getColumnIndex("name"));
    53. }
    54. //3、删除数据
    55. String whereClause = "id like ?";
    56. String[] whereClauseArgs = {"12"};
    57. /**
    58. * delete()方法说明
    59. * 参数一:操作的表名
    60. * 参数二:删除条件
    61. * 参数三:删除条件中对应的值
    62. */
    63. dbRead.delete("students", whereClause, whereClauseArgs);
    64. //4、跟新数据
    65. ContentValues updateContentValues = new ContentValues();
    66. contentValues.put("name", "小花");
    67. String updateSelection = "id = ?";
    68. String[] updateSelectionArgs = {"123456"};//更新条件对应的值,与updateSelection中?顺序一致
    69. /**
    70. * update()方法说明
    71. * 参数一:操作的表名
    72. * 参数二:更新的列对应的值
    73. * 参数三:更新条件
    74. * 参数四:更新条件对应的值
    75. */
    76. dbRead.update("students", updateContentValues, updateSelection, updateSelectionArgs);
    77. dbWrite.close();
    78. dbRead.close();
    79. }
    80. }