Android 數據庫SQLite使用小結

前言

在Android開發過程中,對于數據的存儲,我們或多或少的都會使用到數據庫相關的操作,所以在此小小的總結一下,Android中使用SQLite數據庫的技巧和方法,算是自己對數據庫知識的復習。項目源代碼
本博客同步發布于XueLong的博客

增刪改查

adb shell中操作SQLite

adb shell
su  //以管理員的身份運行命令
sqlite DATABASE_NAME.db //進入要操作的數據庫
.table  //查看當前數據庫有哪些表
.table t% //".tables"命令后也可以跟一參數,它是一個pattern,這樣命令就只列出表名和該參數匹配的表。
.schema //顯示最初用于創建數據庫的CREATE TABLE和CREATE INDEX的SQL語句
.schema t% //".schema"命令可以包含一個參數,它是一個pattern,用于對表進行過濾,這時只會顯示滿足條件的表和所有索引的SQL語句
pragma table_info(TABLE_NAME);  //查看表的數據結構
.mode line  //切換顯示模式,可用參數有 line list column
.separator |   //字段之間使用 | 間隔開
.output filename.txt  //將數據庫中的數據輸出到文件中
.width 12 6 //調整列寬 12表示第一列寬為12,6表示第二列寬為6
.databases //顯示所有當前連接打開的數據庫的一個列表,main:最初打開的數據庫,temp:臨時表的數據庫
.exit //退出

小技巧

  • SQLite EXpert Personal 中注釋SQL語句,單行注釋使用-- ,多行注釋使用/**/
  • 每個 SQLite 數據庫中都有一個隱藏的 sqlite_master 表,它記載了當前數據庫中所有的建表語句。
  • 在對數據庫進行增刪改查前首先需要先調用SQLiteOpenHelpergetReadableDatabase()(查時調用)或getWritableDatabase()(增刪改時調用)方法。

常規的SQL語句操作

SQLiteDatabase db = null;
//在執行增刪改語句時使用
db = helper.getWritableDatabase();
//在執行查詢語句時使用
//db = helper.getReadableDatabase();
db.execSQL("在這里填入你的SQL語句");

常用的SQL語句如下:

//建表語句
create table if not exists TABLE_NAME(Id integer orimary key,Name text,Age integer);
//增加一條數據
insert into TABLE_NAME(Id,Name,Age) values (1,'lixuelong',23);
//刪除一條數據
delete from TABLE_NAME where Name = 'lixuelong';
//修改一條數據
update TABLE_NAME set Name = 'xuelong' where Id =1;
//查詢語句
select * from TABLE_NAME where Name = 'lixuelong' order by Age desc;
//統計查詢語句
select count(Id) from TABLE_NAME where Age = 18;
//比較查詢語句
select Id,Name,Max(Age) as Age from TABLE_NAME;

Android自有的事務(Transaction)處理方法

增加數據操作
long insertOrThrow(String table, String nullColumnHack, ContentValues values)
無論第三個參數是否包含數據,執行此方法必定會插入一條數據

  • table:表名
  • nullColumnHack:用于指定空值字段的名稱
  • values:要存放的ContentValues對象,可以為null
  • 返回值:返回新添記錄的行號,與主鍵id無關,發生錯誤返回-1
SQLiteDatabase db = null;
db = helper.getWritableDatabase();
db.beginTransaction();
// insert into TABLE_NAME (_id,Name,Age) values (6,'張三',18);
ContentValues contentValues = new ContentValues();
contentValues.put("_id","6");
contentValues.put("Name", "張三");
contentValues.put("Age", 18);
db.insertOrThrow(TABLE_NAME, null, contentValues);
db.setTransactionSuccessful();

刪除數據操作
int delete(String table, String whereClause, String[] whereArgs)

  • table:表名
  • whereClause:刪除的條件,如果為null,則整行刪除
  • whereArgs:字符串數組,和whereClause配合使用,有兩種使用方法,1、如果whereClause的條件已經直接給出,如"Name='張三'",則whereArgs可以設為null。2、如果whereClause的條件沒有直接給出,如"Name=?",則?會被whereArgs字符串數組中的值代替。
  • 返回值:0:刪除是被,1:刪除成功
SQLiteDatabase db = null;
db = helper.getWritableDatabase();
db.beginTransaction();
db.delete(TABLE_NAME, "Name=?", new String[]{"張三"});
//db.execSQL("delete from TABLE_NAME where Name = '張三';");
db.setTransactionSuccessful();

修改數據操作
update(String table, ContentValues values, String whereClause, String[] whereArgs)

  • table:表名
  • values:要存放的ContentValues對象,可以為null
  • whereClause:修改的條件,如果為null,則整行修改
  • whereArgs:字符串數組,和whereClause配合使用,有兩種使用方法,1、如果whereClause的條件已經直接給出,如"Name='張三'",則whereArgs可以設為null。2、如果whereClause的條件沒有直接給出,如"Name=?",則?會被whereArgs字符串數組中的值代替。
  • 返回值:the number of rows affected
SQLiteDatabase db = null;
db = helper.getWritableDatabase();
db.beginTransaction();
// update TABLE_NAME set Name = 'zhangsan' where Name = '張三'
ContentValues contentValues = new ContentValues();
contentValues.put("Name", "zhangsan");
db.update(TABLE_NAME, contentValues, "Name = ?", new String[]{"張三"});
db.setTransactionSuccessful();

查詢數據操作
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
query方法較多,這里只列舉一個,有興趣的朋友可以自行研究

  • table:表名
  • columns:需要返回的列的列表,如果為null,則返回全部的列
  • selection:查詢的條件,符合什么條件的行將返回。如果為null,則這個表里的所有行都將返回。其兩種用法和update里的一樣
  • selectionArgs:用法和update里的一樣
  • groupBy:用于控制分組
  • having:用于對分組進行過濾
  • orderBy:用于對記錄進行排序
  • 返回值:Cursor對象
SQLiteDatabase db = null;
Cursor cursor = null;
db = helper.getWritableDatabase();
// select * from TABLE_NAME where Age = 18
cursor = db.query(TABLE_NAME, TABLE_COLUMNS, "Age = ?", new String[]{String.valueOf(18)},null, null, null);
if (cursor.getCount() > 0) {
   List<DBSQLBean> beanList = new ArrayList<DBSQLBean>();
   while (cursor.moveToNext()) {
        DBSQLBean bean = parseBean(cursor);
        beanList.add(bean);
    }
    return beanList;
}

統計查詢數據操作

int count = 0;
SQLiteDatabase db = null;
Cursor cursor = null;
db = helper.getWritableDatabase();
// select count(_id) from TABLE_NAME where Age = 18
cursor = db.query(DBSQLHelper.TABLE_NAME, new String[]{"COUNT(_id)"},"Age = ?", new String[]{String.valueOf(18)},null, null, null);
if (cursor.moveToFirst()) {
    count = cursor.getInt(0);
}

比較查詢數據操作

SQLiteDatabase db = null;
Cursor cursor = null;
db = helper.getWritableDatabase();
// select _id,Name,Max(Age) as Age from TABLE_NAME
cursor = db.query(DBSQLHelper.TABLE_NAME, new String[]{"_id", "Name","Max(Age) as Age"},null, null, null, null, null);
if (cursor.getCount() > 0) {
    if (cursor.moveToFirst()) {
        return parseBean(cursor);
    }
}

寫在最后

以上就是對Android中數據庫操作的小小總結。

如果你在參考過程中遇到問題,可以在我的聯系方式中給我提問。

后面會繼續介紹,Android的相關知識,歡迎繼續關注我博客的更新。

項目源代碼

參考資源

轉載請注明:XueLong的博客 ? Android 數據庫SQLite使用小結

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容