Android-SQLite常见用法操作

一、什么是SQLite
SQLite,是一款轻型的数据库,属于嵌入式和关系型数据库的一种,容纳数据库至2TB, 大概能容纳13万行的C代码,约4.43M
二、SQLite使用的基本步骤

  1. 创建数据库
  2. 操作数据库(增删改查)

三、创建数据库
创建数据库一般有两种方法,一是使用openOrCreateDatabase()方法,二是创建一个SQLiteOpenHelper类来实现,我们常用的方法就是第二种方法,我们简单讲述一下用法。
首先创建一个类继承自SQLiteOpenHelper,随后重写两个方法分别是onCreate和onUpgrade,下面通过代码来具体一看:

package com.dict;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class DBOpenHelper extends SQLiteOpenHelper {

//定义SQL语句,即创建表和列。
    final String CREATE_TABLE_SQL =
            "create table dict(_id integer primary " +
                    "key autoincrement , word , detail)";

    public DBOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, null, version);
    }

// 在onCreate方法中调用SQLiteDatabase去执行SQL语句
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_SQL);
    }
// onUpgrade方法主要用于显示版本更新,这个我们打个log看看即可
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i("database", "----版本更新"+oldVersion+"--->"+newVersion);
    }
}

这个我们比较简易的来实现了数据库的创建,实际项目中,非常建议大家先将数据库的表名,列名单独以静态常量的方式提前声明,SQL的直接语句在onCreate方法中进行即可。像下面这种形式

	public static final String TABLE_NAME_NOTES = "notes";
	public static final String TABLE_NAME_MEDIA = "media";
	public static final String COLUMN_NAME_ID = "_id";
	public static final String COLUMN_NAME_NOTE_NAME = "name";
	public static final String COLUMN_NAME_NOTE_CONTENT = "content";
	public static final String COLUMN_NAME_NOTE_DATE = "date";
	public static final String COLUMN_NAME_MEDIA_PATH = "path";
	public static final String COLUMN_NAME_MEDIA_OWNER_NOTE_ID = "note_id";

四、操作数据库
在了解如何操作数据库之前,我们先去了解两个方法,分别是
getReadableDatabase()和getWritableDatabase()。
getReadableDatabase() 方法则是先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,当打开失败后会继续尝试以只读方式打开数据库。如果该问题成功解决,则只读数据库对象就会关闭,然后返回一个可读写的数据库对象。
getWritableDatabase() 方法以读写方式打开数据库,一旦数据库的磁盘空间满了,数据库就只能读而不能写,倘若使用的是getWritableDatabase() 方法就会出错。

1.增
对数据表的添加采用insert()方法,insert()方法里有三个参数,分别是
String table, String nullColumnHack, ContentValues values
见名知意,第一个参数是表名,第二参数是当insert插入值为空时,自动填入null,第三个就是插入的值。
2.删
对数据表的删除采用delete()方法,delete()方法中同样存在三个参数,分别是String table, String whereClause, String[] whereArgs
第一个参数是所要删除的表名,第二个是可选的where语句,第三个是占位参数列表。例如下面这段代码所示。

ContentValues cv = new ContentValues();
String[] args = {String.valueOf("c")};
delete("user", "username=?", args);

3.改
改即对数据表的更新,使用update()方法,里面含有四个参数,分别是
String table, ContentValues values, String whereClause, String[] whereArgs
这里不再进行说明

ContentValues cv = new ContentValues();
cv.put("username", "c");
cv.put("password", "d");
String[] args = {String.valueOf("a")};
update("user", cv, "username=?",args)

4查
对数据表的查询,通常使用query方法进行查询,query方法有10个参数,分别是
boolean distinct,
String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit,
CancellationSignal cancellationSignal
其含义如下
1 distinct,boolean: true if you want each row to be unique, false otherwise.(设置为true,每一行的数据必须唯一。反之亦然。)
2. table,String: The table name to compile the query against.(query函数要操作的表名。)
3. columns,String[]: A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn’t going to be used.(要返回的列的名字的数组。如果设置为null,返回所有列,如果不需要使用所有列,不建议这么做。)
4. selection,String: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.(一个决定返回哪一行的过滤器,相当于SQL语句中的 WHERE 关键字。传递null则会返回给定表的所有行。)
5. selectionArgs,String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.(用于替换上一个参数中的 ? ,顺序对应selection中?的顺序。格式限制为String格式。)
6. groupBy,String: A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.(用于设定返回行的分组方式,相当于SQL语句中的GROUP BY 关键字。传递null表示返回的行不会被分组。)
7. having,String: A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.(决定哪一行被放到Cursor中的过滤器。如果使用了行分组,相当于SQL语句中的HAVING关键字。传递null会导致所有的行都包含在内,前提是groupBy属性也设置为null。)
8. orderBy,String: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.(行的排列方式,相当于SQL语句中的“ORDER BY”关键字,传递null表示使用默认的排序方式,可能是无序排列。)
9. limit,String: Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.(设置query语句返回行的数量,相当于SQL语句中的“LIMIT”关键字,传递null表示没有设置limit语句。注意格式为String,传递的时候需要传递数字字符串,例如“12”)
10. cancellationSignal,CancellationSignal: A signal to cancel the operation in progress, or null if none. If the operation is canceled, then OperationCanceledException will be thrown when the query is executed.(取消程序操作的信号,如果没有则设置为null。如果操作取消了,query语句运行时会抛出OperationCanceledException异常。)
值得注意的是,这些操作的返回值都是一个Cursor对象,需要拿到cursor的值时,通过cursor.getString方法来获取。
另外,使用这些方法必须先实例化一个SQLiteOpenHelper类的对象,通过对象的getReadableDatabase()或getWritableDatabase()来调用。
给大家一个实例,是一个简易词典的实现:
在这里插入图片描述
在这里插入图片描述
下载链接如下:
简易词典

猜你喜欢

转载自blog.csdn.net/qq_43704563/article/details/106609948