Android 中SQLite数据库的使用详解

简介: Android 中SQLite数据库的使用详解

Android SQLite数据库相关API的介绍可以看这篇文章

Android SQLite数据库中基础的增删改查操作以及API的详解

效果如图所示:

一、向数据库中写入数据

1.首先创建数据库user和表user_info,详细的注释已经在代码中给出

public class UserDBHelper extends SQLiteOpenHelper {
    private static final String TAG = "UserDBHelper";
    //声明数据库帮助器的实例
    public static UserDBHelper userDBHelper = null;
    //声明数据库的实例
    private SQLiteDatabase db = null;
    //声明数据库的名称
    public static final String DB_NAME = "user.db";
    //声明表的名称
    public static final String TABLE_NAME = "user_info";
    //声明数据库的版本号
    public static int DB_VERSION = 1;
    public UserDBHelper(@Nullable Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
    public UserDBHelper(@Nullable Context context, int version) {
        super(context, DB_NAME, null, version);
    }
    //利用单例模式获取数据库帮助器的实例
    public static UserDBHelper getInstance(Context context, int version) {
        if (userDBHelper == null && version > 0) {
            userDBHelper = new UserDBHelper(context, version);
        } else if (userDBHelper == null) {
            userDBHelper = new UserDBHelper(context);
        }
        return userDBHelper;
    }
    //打开数据库的写连接
    public SQLiteDatabase openWriteLink() {
        if (db == null || !db.isOpen()) {
            db = userDBHelper.getWritableDatabase();
        }
        return db;
    }
  //getWritableDatabase()与getReadableDatabase() 这两个方法都可以获取到数据库的连接
  //正常情况下没有区别,当手机存储空间不够了
  //getReadableDatabase()就不能进行插入操作了,执行插入没有效果
  //getWritableDatabase():也不能进行插入操作,如果执行插入数据的操作,则会抛异常。对于现在来说不会出现这种情况,用哪种方式都可以
    //打开数据库的读连接
    public SQLiteDatabase openReadLink() {
        if (db == null || !db.isOpen()) {
            db = userDBHelper.getReadableDatabase();
        }
        return db;
    }
    //关闭数据库的读连接
    public void closeLink() {
        if (db != null && db.isOpen()) {
            db.close();
            db = null;
        }
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        //如果存在user_info表,则删除该表
        String drop_sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
        db.execSQL(drop_sql);
        //创建user_info表
        String create_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
                + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "name VARCHAR NOT NULL,"
                + "age INTEGER NOT NULL,"
                + "height INTEGER NOT NULL,"
                + "weight DECIMAL(10,2) NOT NULL,"
                + "married INTEGER NOT NULL,"
                + "update_time VARCHAR NOT NULL"
                + ");";
        db.execSQL(create_sql);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
    //根据指定条件删除表记录
    public int delete(String condition) {
        // 执行删除记录动作,该语句返回删除记录的数目
        //参数一:表名
        //参数二:whereClause where子句
        //参数三:whereArgs 您可以在 where 子句中包含 ?s,
        // 它将被 whereArgs 中的值替换。这些值将绑定为字符串。
        return db.delete(TABLE_NAME, condition, null);
    }
    //删除该表所有记录
    public int deleteAll() {
        // 执行删除记录动作,该语句返回删除记录的数目
        return db.delete(TABLE_NAME, "1=1", null);
    }
    // 往该表添加一条记录
    public long insert(UserInfo userInfo) {
        List<UserInfo> infoList = new ArrayList<>();
        infoList.add(userInfo);
        return insert(infoList);
    }
    // 往该表添加多条记录
    public long insert(List<UserInfo> infoList) {
        long result = -1;
        for (int i = 0; i < infoList.size(); i++) {
            UserInfo userInfo = infoList.get(i);
            List<UserInfo> tempList = new ArrayList<>();
            // 如果存在同名记录,则更新记录
            // 注意条件语句的等号后面要用单引号括起来
            if (userInfo.name != null && userInfo.name.length() > 0) {
                String condition = String.format("name='%s'", userInfo.name);
                tempList = query(condition);
                if (tempList.size() > 0) {
                    update(userInfo, condition);
                    result = tempList.get(0).rowid;
                    continue;
                }
            }
            // 不存在唯一性重复的记录,则插入新记录
            ContentValues cv = new ContentValues();
            cv.put("name", userInfo.name);
            cv.put("age", userInfo.age);
            cv.put("height", userInfo.height);
            cv.put("weight", userInfo.weight);
            cv.put("married", userInfo.married);
            cv.put("update_time", userInfo.update_time);
            // 执行插入记录动作,该语句返回插入记录的行号
            //参数二:参数未设置为NULL,参数提供可空列名称的名称,以便在 cv 为空的情况下显式插入 NULL。
            //参数三:values 此映射包含行的初始列值。键应该是列名,值应该是列值
            result = db.insert(TABLE_NAME, "", cv);
            // 添加成功则返回行号,添加失败则返回-1
            if (result == -1) {
                return result;
            }
        }
        return result;
    }
    //根据条件更新指定的表记录
    public int update(UserInfo userInfo, String condition) {
        ContentValues cv = new ContentValues();
        cv.put("name", userInfo.name);
        cv.put("age", userInfo.age);
        cv.put("height", userInfo.height);
        cv.put("weight", userInfo.weight);
        cv.put("married", userInfo.married);
        cv.put("update_time", userInfo.update_time);
        //执行更新记录动作,该语句返回更新的记录数量
        //参数二:values 从列名到新列值的映射
        //参数三:whereClause 更新时要应用的可选 WHERE 子句
        //参数四:whereArgs 您可以在 where 子句中包含 ?s,
        //它将被 whereArgs 中的值替换。这些值将绑定为字符串。
        return db.update(TABLE_NAME, cv, condition, null);
    }
    public int update(UserInfo userInfo) {
        // 执行更新记录动作,该语句返回更新的记录数量
        return update(userInfo, "rowid=" + userInfo.rowid);
    }
    public List<UserInfo> query(String condition) {
        String sql = String.format("select rowid,_id,name,age,height,weight,married,update_time" +
                " from %s where %s;", TABLE_NAME, condition);
        List<UserInfo> infoList = new ArrayList<>();
        // 执行记录查询动作,该语句返回结果集的游标
        //参数一:SQL查询
        //参数二:selectionArgs
        //您可以在查询的 where 子句中包含 ?s,它将被 selectionArgs 中的值替换。这些值将绑定为字符串。
        Cursor cursor = db.rawQuery(sql, null);
        // 循环取出游标指向的每条记录
        while (cursor.moveToNext()) {
            UserInfo userInfo = new UserInfo();
            //Xxx getXxx(columnIndex):根据字段下标得到对应的值
            //int getColumnIndex():根据字段名得到对应的下标
            //cursor.getLong():以 long 形式返回所请求列的值。
            //getColumnIndex() 获取给定列名的从零开始的列索引,如果列名不存在返回-1
            userInfo.name = cursor.getString(cursor.getColumnIndex("name"));
            userInfo.age = cursor.getInt(cursor.getColumnIndex("age"));
            userInfo.height = cursor.getLong(cursor.getColumnIndex("height"));
            userInfo.weight = cursor.getFloat(cursor.getColumnIndex("weight"));
            //SQLite没有布尔型,用0表示false,用1表示true
            userInfo.married = (cursor.getInt(cursor.getColumnIndex("married")) == 0) ? false : true;
            userInfo.update_time = cursor.getString(cursor.getColumnIndex("update_time"));
            infoList.add(userInfo);
        }
        //查询完毕,关闭数据库游标
        cursor.close();
        return infoList;
    }
}

2.创建UserInfo实体类

//用户信息
public class UserInfo {
    public long rowid; // 行号
    public int xuhao; // 序号
    public String name; // 姓名
    public int age; // 年龄
    public long height; // 身高
    public float weight; // 体重
    public boolean married; // 婚否
    public String update_time; // 更新时间
    public UserInfo() {
        rowid = 0L;
        xuhao = 0;
        name = "";
        age = 0;
        height = 0L;
        weight = 0.0f;
        married = false;
        update_time = "";
    }
}

3.创建布局页面activity_sqilte_write.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp"
    tools:context=".SqilteWriteActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp">
        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="姓名:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/edit_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_toRightOf="@+id/tv_name"
            android:background="@drawable/edit_style"
            android:gravity="center|left"
            android:hint="请输入姓名"
            android:inputType="text"
            android:maxLength="12"
            android:textSize="17sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp">
        <TextView
            android:id="@+id/tv_age"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="年龄:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/edit_age"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_toRightOf="@+id/tv_age"
            android:background="@drawable/edit_style"
            android:gravity="center|left"
            android:hint="请输入年龄"
            android:inputType="number"
            android:maxLength="2"
            android:textSize="17sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp">
        <TextView
            android:id="@+id/tv_height"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="身高:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/edit_height"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_toRightOf="@+id/tv_height"
            android:background="@drawable/edit_style"
            android:gravity="center|left"
            android:hint="请输入身高"
            android:inputType="number"
            android:maxLength="3"
            android:textSize="17sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp">
        <TextView
            android:id="@+id/tv_weight"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="体重:"
            android:textColor="@color/black"
            android:textSize="17sp" />
        <EditText
            android:id="@+id/edit_weight"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_toRightOf="@+id/tv_weight"
            android:background="@drawable/edit_style"
            android:gravity="center|left"
            android:hint="请输入体重"
            android:inputType="numberDecimal"
            android:maxLength="5"
            android:textSize="17sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp">
        <CheckBox
            android:id="@+id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/checkbox"
            android:gravity="center"
            android:text="已婚"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </RelativeLayout>
    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存到数据库"
        android:textColor="@color/black"
        android:textSize="17sp" />
</LinearLayout>

4.创建SqilteWriteActivity类添加数据

public class SqilteWriteActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private EditText edit_name;
    private EditText edit_age;
    private EditText edit_height;
    private EditText edit_weight;
    private CheckBox checkbox;
    private Button btn_save;
    private boolean isMarried = false;
    //声明数据库帮助器的对象
    private UserDBHelper userDBHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqilte_write);
        edit_name = findViewById(R.id.edit_name);
        edit_age = findViewById(R.id.edit_age);
        edit_height = findViewById(R.id.edit_height);
        edit_weight = findViewById(R.id.edit_weight);
        checkbox = findViewById(R.id.checkbox);
        checkbox.setOnCheckedChangeListener(this);
        btn_save = findViewById(R.id.btn_save);
        btn_save.setOnClickListener(this);
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        isMarried = isChecked;
    }
    @Override
    protected void onStart() {
        super.onStart();
        userDBHelper = UserDBHelper.getInstance(this, 1);
        //打开数据库帮助器的写连接
        userDBHelper.openWriteLink();
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_save) {
            String name = edit_name.getText().toString();
            String age = edit_age.getText().toString();
            String height = edit_height.getText().toString();
            String weight = edit_weight.getText().toString();
            if (TextUtils.isEmpty(name)) {
                ToastUtil.show(this, "请先填写姓名");
                return;
            } else if (TextUtils.isEmpty(age)) {
                ToastUtil.show(this, "请先填写年龄");
                return;
            } else if (TextUtils.isEmpty(height)) {
                ToastUtil.show(this, "请先填写身高");
                return;
            } else if (TextUtils.isEmpty(weight)) {
                ToastUtil.show(this, "请先填写体重");
                return;
            }
            UserInfo userInfo = new UserInfo();
            userInfo.name = name;
            userInfo.age = Integer.parseInt(age);
            userInfo.height = Long.parseLong(height);
            userInfo.weight = Float.parseFloat(weight);
            userInfo.married = isMarried;
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = sdf.format(new Date());
            userInfo.update_time = nowTime;
            userDBHelper.insert(userInfo);
            ToastUtil.show(this, "数据已写入SQLite数据库");
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        userDBHelper.closeLink();
    }
}

以上就是添加数据的代码详解

二、读取数据库中的数据

1.布局页面activity_sqlite_read.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SqliteReadActivity">
    <Button
        android:id="@+id/btn_delete_all"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除所有记录"
        android:textColor="@color/black"
        android:textSize="17sp" />
    <TextView
        android:id="@+id/tv_sqlite"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:textColor="@color/black"
        android:textSize="17sp" />
</LinearLayout>

2.创建SqliteReadActivity类显示数据库中的数据,并且实现删除功能

public class SqliteReadActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_delete_all;
    private TextView tv_sqlite;
    //声明数据库帮助器的实例
    private UserDBHelper userDBHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite_read);
        btn_delete_all = findViewById(R.id.btn_delete_all);
        btn_delete_all.setOnClickListener(this);
        tv_sqlite = findViewById(R.id.tv_sqlite);
    }
    @Override
    protected void onStart() {
        super.onStart();
        //获得数据库帮助器的实例
        userDBHelper = UserDBHelper.getInstance(this, 1);
        //打开数据库帮助器的读连接
        userDBHelper.openReadLink();
        // 读取数据库中保存的所有用户记录
        readSQLite();
    }
    @SuppressLint("DefaultLocale")
    private void readSQLite() {
        if (userDBHelper == null) {
            ToastUtil.show(this, "数据库连接为空!");
            return;
        }
        // 执行数据库帮助器的查询操作
        List<UserInfo> userInfoList = userDBHelper.query("1=1");
        String desc = String.format("数据库查询到%d条记录,详情如下:", userInfoList.size());
        for (int i = 0; i < userInfoList.size(); i++) {
            UserInfo userInfo = userInfoList.get(i);
            desc = String.format("%s\n第%d条记录信息如下:", desc, i + 1);
            desc = String.format("%s\n 姓名为%s", desc, userInfo.name);
            desc = String.format("%s\n 年龄为%d", desc, userInfo.age);
            desc = String.format("%s\n 身高为%d", desc, userInfo.height);
            desc = String.format("%s\n 体重为%f", desc, userInfo.weight);
            desc = String.format("%s\n 婚否为%b", desc, userInfo.married);
            desc = String.format("%s\n 更新时间为%s", desc, userInfo.update_time);
        }
        if (userInfoList.size() <= 0) {
            desc = "数据库查询到的记录为空";
        }
        tv_sqlite.setText(desc);
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_delete_all) {
            //关闭数据库连接
            userDBHelper.closeLink();
            //打开数据库帮助器的写连接
            userDBHelper.openWriteLink();
            //删除所有记录
            userDBHelper.deleteAll();
            //关闭数据库连接
            userDBHelper.closeLink();
            //打开数据库帮助器的读连接
            userDBHelper.openReadLink();
            //读取数据库中保存的所有用户记录
            readSQLite();
            ToastUtil.show(this, "已删除所有记录");
        }
    }
}

以上就是显示数据库中的数据的详细步骤,和删除数据的步骤~


目录
相关文章
|
1月前
|
API 数据库 C语言
【C/C++ 数据库 sqlite3】SQLite C语言API返回值深入解析
【C/C++ 数据库 sqlite3】SQLite C语言API返回值深入解析
170 0
|
1月前
|
网络协议 关系型数据库 MySQL
如何实现无公网ip远程访问本地安卓Termux部署的MySQL数据库【内网穿透】
如何实现无公网ip远程访问本地安卓Termux部署的MySQL数据库【内网穿透】
|
2月前
|
存储 监控 安全
内网屏幕监控软件的数据存储与管理:使用SQLite数据库保存监控记录和配置信息
在当今数字化时代,安全和监控在企业和组织中变得至关重要。内网屏幕监控软件作为一种关键工具,帮助组织监视员工的活动并确保信息安全。这种软件不仅需要高效地记录和管理监控数据,还需要能够方便地进行配置和调整。本文将讨论如何使用SQLite数据库来保存监控记录和配置信息,并介绍如何通过自动化机制将监控到的数据提交到指定网站。
165 2
|
13天前
|
SQL 关系型数据库 数据库
Python中SQLite数据库操作详解:利用sqlite3模块
【4月更文挑战第13天】在Python编程中,SQLite数据库是一个轻量级的关系型数据库管理系统,它包含在一个单一的文件内,不需要一个单独的服务器进程或操作系统级别的配置。由于其简单易用和高效性,SQLite经常作为应用程序的本地数据库解决方案。Python的内置sqlite3模块提供了与SQLite数据库交互的接口,使得在Python中操作SQLite数据库变得非常容易。
|
18天前
|
关系型数据库 MySQL 数据库连接
Python+SQLite数据库实现服务端高并发写入
Python中使用SQLite内存模式实现高并发写入:创建内存数据库连接,建立表格,通过多线程并发写入数据。虽然能避免数据竞争,但由于SQLite内存模式采用锁机制,可能在高并发时引发性能瓶颈。若需更高性能,可选择MySQL或PostgreSQL。
23 0
|
1月前
|
关系型数据库 数据库 C++
嵌入式数据库sqlite3【基础篇】基本命令操作,小白一看就懂(C/C++)
嵌入式数据库sqlite3【基础篇】基本命令操作,小白一看就懂(C/C++)
|
1月前
|
存储 SQL 数据库
django如何连接sqlite数据库?
django如何连接sqlite数据库?
51 0
|
1月前
|
存储 SQL 数据库
【Android 从入门到出门】第六章:使用Room数据库并测试
【Android 从入门到出门】第六章:使用Room数据库并测试
31 4
|
1月前
|
网络协议 关系型数据库 MySQL
安卓手机termux上安装MariaDB数据库并实现公网环境下的远程连接
安卓手机termux上安装MariaDB数据库并实现公网环境下的远程连接
|
2月前
|
数据库 Android开发 数据库管理
【Android】使用android studio查看内置数据库信息
【Android】使用android studio查看内置数据库信息
76 0

热门文章

最新文章