Android數據持久化技術之Sqlite3的使用

https://blog.csdn.net/qq_43230007/article/details/105005060

目錄

  • 一、Sqlite簡單的使用
  • 二、Sqlite表創建
  • 三、Sqlite表升級
  • 四、Sqlite的存儲數據(insert)
  • 五、Sqlite更新和刪除(update、delete)
  • 六、Sqlite查詢(query)
  • 七、Sqlite聚合函數使用(count、sum、max、min、average)

說明:這些都是Sqlite中比較傳統的用法,使用起來比較麻煩。博主推薦使用LitPal會大大方便sqlite的數據庫操作,如果有興趣的小夥伴可參考下面兩篇文章。

文章一(簡短敘述):https://blog.csdn.net/qq_43230007/article/details/105005060
文章二(詳細述說原理):https://blog.csdn.net/sinyu890807/category_9262963.html

一、Sqlite簡單的使用

  1. 進入adb目錄,輸入 adb shell

  2. 進入data/data目錄,然後進入指定的包路徑 如:com.example.provider

  3. 進入databases目錄,然後 ls 查看數據庫

  4. 選擇(或者創建)一個數據庫進入 sqlite3 {databaseName}

  5. 一些簡單常用的命令

  • .table 查詢當前數據庫下面的所有表
  • .help 查看幫助
  • pragma table_info(TABLE_NAME) 查詢選中表的字段屬性,等價於MySql中的desc {tableName}命令
  • .mode line 切換顯示模式
  1. 一些常用Sql的CRUD命令,學過SQL的應該都會(CRUD)
  • create table {tableName}(id integer,name text);
  • insert into {tabeName}[(…)] values(…);
  • delete from {tableName} where {條件};
  • update {tableName} set {…} where {條件};
  • drop table {table_name};

二、Sqlite表創建

  1. 需要創建一個繼承自SQLiteOpenHelper的類,然後重寫其中的onCreate方法並且創建一張表
public class MySQLiteHelper extends SQLiteOpenHelper {

	public static final String CREATE_NEWS = "create table news ("
			+ "id integer primary key autoincrement, "
			+ "title text, "
			+ "content text, "
			+ "publishdate integer,"
			+ "commentcount integer)";

	public MySQLiteHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_NEWS);
	}
    ...
}
  1. 通常我們在Activity類中會通過這個方法進行數據庫的初始化
//1.數據庫初始化操作,參數一是context,參數二是數庫庫名稱,參數三是當前版本version
SQLiteOpenHelper dbHelper = new MySQLiteHelper(this, "demo.db", null, 1);
//2.獲取數據庫操作類對象SQLiteDatabase,通過這個對象我們就可以進行CRUD操作了
SQLiteDatabase db = dbHelper.getWritableDatabase();

三、Sqlite表升級

  • 場景:當數據庫的表的數量或者一些列字段需要變更的時候,我們需要對數據庫進行版本迭代,實現方式如下
  1. 傳統方法的升級邏輯通常是通過重寫SQLiteOpenHelper中的onUpgrade方法來根據版本迭代邏輯進行更新
  • 爲何不在onCreate方法中進行更新,因爲該方法僅僅在軟件第一次啓動時執行一次,是不會再執行第二次的。

  • 在Android機制中數據庫更新(通常指數據表的增加,表的字段的改變)邏輯通常是依賴於版本更迭的

public class MySQLiteHelper extends SQLiteOpenHelper {

	......

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_NEWS);
		db.execSQL(CREATE_COMMENT);
	}

	@Override//根據newVersion的迭代邏輯進行數據庫更新
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		switch (oldVersion) {
		case 1:
			db.execSQL(CREATE_COMMENT);
		default:
		}
	}

}
//進行版本迭代,需要更改版本號。第三個參數變爲2
SQLiteOpenHelper dbHelper = new MySQLiteHelper(this, "demo.db", null, 2);
SQLiteDatabase db = dbHelper.getWritableDatabase();
  • 注意:Sqlite語法中沒有直接刪除列的操作,通常無視需要刪除的列(如果需要刪除需要繞彎)

四、Sqlite的存儲數據(insert)

  1. insert方法
//方法,第一個參數是表名,第二個參數通常都用不到,直接傳null,第三個參數則是一個封裝了待存儲數據的ContentValues對象
//返回該行插入的數據id
public long insert(String table, String nullColumnHack, ContentValues values)
//示例
//其中,調用ContentValues的put()方法來添加待存儲數據,put()方法接收兩個參數,第一個參數是數據庫表中對應的列名,第二個參數就是要存儲的值
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", "這是一條新聞標題");
values.put("content", "這是一條新聞內容");
values.put("publishdate", System.currentTimeMillis());
long id = db.insert("news", null, values);

五、Sqlite更新和刪除(update、delete)

  1. update()方法的使用
//update()方法接收四個參數,第一個參數是表名,第二個參數是一個封裝了待修改數據的ContentValues對象,第三和第四個參數用於指定修改哪些行,對應了SQL語句中的where部分。
public int update(String table, ContentValues values, String whereClause, String[] whereArgs)
//示例
//update news set title='今日iPhone6發佈' where id=2;
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", "今日iPhone6發佈");
db.update("news", values, "id = ?", new String[] {"2"});
  1. delete()方法
//delete()方法接收三個參數,第一個參數同樣是表名,第二和第三個參數用於指定刪除哪些行,對應了SQL語句中的where部分。
public int delete(String table, String whereClause, String[] whereArgs)
//delete from news where commentcount=0;
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("news", "commentcount = ?", new String[] {"0"});

六、Sqlite查詢(query)

//1. 通過原生方法進行查詢
//rawQuery()方法接收兩個參數,第一個參數接收的就是一個SQL字符串,第二個參數是用於替換SQL語句中佔位符(?)的字符串數組。rawQuery()方法返回一個Cursor對象,所有查詢到的數據都是封閉在這個對象當中的,我們只要一一取出就可以了。
public Cursor rawQuery(String sql, String[] selectionArgs)
//2. 通過重載方法進行查詢,重載形式還有很多
//第二個參數用於指定去查詢哪幾列,如果不指定則默認查詢所有列。第三、第四個參數用於去約束查詢某一行或某幾行的數據,不指定則默認是查詢所有行的數據。第五個參數用於指定需要去group by的列,不指定則表示不對查詢結果進行group by操作。第六個參數用於對group by之後的數據進行進一步的過濾,不指定則表示不進行過濾。第七個參數用於指定查詢結果的排序方式,不指定則表示使用默認的排序方式。
public Cursor query(String table, String[] columns, String selection,
            String[] selectionArgs, String groupBy, String having,
            String orderBy)
//示例
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("news", null, "commentcount>?", new String[]{"0"}, null, null, null);
List<News> newsList = new ArrayList<News>();
if (cursor != null && cursor.moveToFirst()) {
	do {
		int id = cursor.getInt(cursor.getColumnIndex("id"));
		String title = cursor.getString(cursor.getColumnIndex("title"));
		String content = cursor.getString(cursor.getColumnIndex("content"));
		Date publishDate = new Date(cursor.getLong(cursor.getColumnIndex("publishdate")));
		int commentCount = cursor.getInt(cursor.getColumnIndex("commentcount"));
		News news = new News();
		news.setId(id);
		news.setTitle(title);
		news.setContent(content);
		news.setPublishDate(publishDate);
		news.setCommentCount(commentCount);
		newsList.add(news);
	} while (cursor.moveToNext());
}

七、Sqlite聚合函數使用(count、sum、max、min、average)

  • 雖說是聚合函數,但它的用法其實和傳統的查詢還是差不多的,即仍然使用的是select語句。但是在select語句當中我們通常不會再去指定列名,而是將需要統計的列名傳入到聚合函數當中,那麼執行select語句使用的還是SQLiteDatabase中的rawQuery()方法。
  1. count()
//其中count(1)就是用於去統計一共有多少行的。當然這裏並不一定要用count(1),使用count(*)或者count(主鍵)都可以。
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor c = db.rawQuery("select count(1) from news", null);
if (c != null && c.moveToFirst()) {
	int count = c.getInt(0);
	Log.d("TAG", "result is " + count);
}
c.close();
  1. sum()
//
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor c = db.rawQuery("select sum(commentcount) from news", null);
if (c != null && c.moveToFirst()) {
	int count = c.getInt(0);
	Log.d("TAG", "result is " + count);
}
c.close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章