GVKun编程网logo

跟我学Android之十三 SQLite数据库操作

9

如果您对跟我学Android之十三SQLite数据库操作感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于跟我学Android之十三SQLite数据库操作的详细内容,并且为您提

如果您对跟我学Android之十三 SQLite数据库操作感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于跟我学Android之十三 SQLite数据库操作的详细内容,并且为您提供关于Android SQLite3 数据库操作、Android Sqlite数据库中基础的增删改查操作、Android SQLite数据库加密的操作方法、Android SQLite数据库操作代码类分享的有价值信息。

本文目录一览:

跟我学Android之十三 SQLite数据库操作

跟我学Android之十三 SQLite数据库操作

视频课:https://edu.csdn.net/course/play/7621

本章内容

第 1 节  sqlite 数据库概述

第 2 节  sqlite 建库建表

第 3 节 管理数据库连接

第 4 节   操作数据库数据

第 5 节   数据绑定

本章目标

掌握 sqlite 数据的基本特点与工具使用。

熟练掌握 sqlite 建库建表的方法。

熟练掌握连接 sqlite 数据库的方法。

熟悉 sqlite 数据库的升级与建立方法。

掌握通过数据绑定完成数据显示的方法。

sqlite数据库简介

sqlite是一种非常流行的嵌入式数据库,是由C语言编写而成,是一款轻型关系型数据库,支持sql,支持多种操作系统,完全独立运行,没有依赖性,Android内嵌了sqlite数据库。 

sqlite数据库工具是用来操作数据库文件的工具,官方网站提供了命令行工具的下载。 

http://www.sqlite.org/download.html

下载sqlite-shell-******.zip文件

解压缩后只有一个文件sqlite3,将sqlite3所在的路径加入path环境变量,sqlite3工具的使用,连接数据库文件。

$ sqlite3 <数据库文件路径>

sqlite数据库工具是用来操作数据库文件的工具

usqlite3工具的使用

Ø数据库的相关管理命令都是以.开头,常用命令如下

 

sqlite数据库工具是用来操作数据库文件的工具

sqlite3工具的使用,在sqlite3的命令行下可以直接输入标准sql语句,除了sqlite3以外,还有很多非官方的可视化管理工具

sqlite Database browser

sqlite Expert Professional

sqlite Develope

sqlite与大型数据库的区别

两者都是支持关系的关系型数据库,sqlite是一个嵌入型的轻量级数据库,适合小数据量,大型数据库独立运行在数据库服务器上,适合大数据量级别,大型数据库通常以网络的方式对外提供服务。

创建 sqlite 数据库 

$ sqlite3test.db

直接在命令行输入上面的命令,如果test.db不存在,则预创建(直到执行相关sql才创建文件),如果test.db存在,则连接数据库 

$ sqlite3test.db <sql.script

上述命令可以在创建数据库的同时使用sql.script进行初始化 

sqlite数据库的数据类型

sqlite数据中的列可以存储任意数据类型的数据

为了与其他数据库兼容,可以为字段指定默认的类型

NULL:空值

INTEGER: 带符号的整数,具体取决于存入数字的范围大小

REAL:浮点数,存储为8-bytes的浮点数

TEXT:字符串文本

BLOB:二进制对象

同时还接受如下一些类型:

smallint 16位整数

int 32位整数

float 32位浮点数

double 64位浮点数

sqlite数据库的数据类型

为了与其他数据库兼容,可以为字段指定默认的类型

同时还接受如下一些类型:

char(n) n不能炒作254

varchar(n) n不能超过4000

date

time

limestamp

创建sqlite数据表,通过sql语句创建表 

create table books (id integer primary key autoincrement,name varchar(128) not null unique,author varchar(128) not null,price double not null);

创建表间关联(也就是通过外键建立关系)

create table groups(id integer primary key autoincrement,name varchar(128) not null unique);crate table users(id integer primary key autoincrement,group_id integer constraint fk_users_group_id references groups(id),username varchar(128) not nullpassword varchar(128) not null);

事务控制

sqlite支持数据库事务

sqlite> begin;sqlite> insert into ……sqlite> commit;sqlite> rollabck;

Android系统中sqlite数据库文件的保存位置

默认情况下,数据库文件保存在如下目录中:

/data/data/<应用程序包>/databases

用户也可以指定将文件保存在任意有权限的目录中,通常SD卡中的目录都可以,在Android系统中连接数据库,使用sqliteDatabase类连接数据库

sqliteDatabase  db = sqliteDatabase.openorCreateDatabase(dbFile, null);

通过sqliteOpenHelper类来连接数据库

public class MyHelper extends sqliteOpenHelper {public static final int VERSION = 1;public static final String DATABASE_NAME = “test.db”;public MyHelper(Context context) {super(context, DATABASE_NAME, null, VERSION);}}
sqliteDatabase  db = helper.getWritableDatabase();

数据库升级与存在性检测,当应用升级的时候,需要检测数据库是否存在,或者是否要升级,sqliteOpenHelper提供了创建与升级的能力

public MyHelper(Context context) {super(context, DATABASE_NAME, null, VERSION);}

覆盖onCreate(sqliteDatabase db)方法,完成创建任务

public void onCreate(sqliteDatabase db) {String str_sql = "CREATE TABLE " + TABLE_NAME+ "(” + ID                 + " INTEGER PRIMARY KEYAUTOINCREMENT,”+ TEXT + " text);";db.execsql(str_sql);}

数据库升级与存在性检测,覆盖onUpdate方法,完成升级任务

public void onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) {//这里填写数据库升级操作的代码}

合理关闭数据库连接

不再使用或长时间不用时,应关闭数据库连接

程序退出时

程序暂停时

不再需要操作数据库时

使用sqliteDatabase类中的close方法关闭连接

执行查询(假设已经存在了数据库连接句柄db)

在sqliteDatabase中提供了如下方法用于查询

execsql

insert、insertOrThrow、insertWithOnConflict

query、rawQuery

replace、replaceOrThrow

update、updateWithOnConflict

delete

执行查询(假设已经存在了数据库连接句柄db),插入记录示例

//将一条新记录的各个字段内容装入一个ContentValues对象ContentValues cv = new ContentValues();cv.put("name",user.getName());cv.put("age",user.getAge());cv.put("remark",user.getRemark());//插入一条新记录db.insert("users",null, cv);

执行查询(假设已经存在了数据库连接句柄db)

u删除记录示例

//第一个参数为表名//第二个参数表示where后的条件表达式,可以使用?//第三个参数则是一个对应每一个?值的数组db.delete("users", "id=?", new String[]{String.valueOf(userId)});

更新记录示例

ContentValues cv = new ContentValues();cv.put("name", user.getName());cv.put("age", user.getAge());cv.put("remark", user.getRemark());db.update("users", cv, "id=?",new String[]{String.valueOf(userId)});

执行查询(假设已经存在了数据库连接句柄db)

u单表查询所有记录示例

Cursor c = db.query("users", null, null, null, null, null, "name");List<User> users = null;if(c != null) {users = new ArrayList<User>();while(c!=null && c.movetoNext()) {User u = new User();u.setId(c.getInt(0));u.setName(c.getString(1));u.setAge(c.getInt(2));u.setRemark(c.getString(3));users.add(u);}c.close();}

执行查询(假设已经存在了数据库连接句柄db)

单表条件查询记录示例

Cursor c = db.query(“users”,  //表名new String[]{“name”, “age”}, //select包含的字段 “age > ?”,  //where条件表达式new String[]{“10”},  //条件值null,  //group子句null,  //having子句“name desc” //排序字段);



执行查询(假设已经存在了数据库连接句柄db)

任意sql条件查询记录示例

String sql = “select name, age from users where age > ?”Cursor c = db.query(sqlnew String[]{“10”});

事务是确保数据库操作原子性的保障

sqliteDatabase提供了如下方法用于事务处理

beginTransaction 开启事务

setTransactionSuccessful 提交事务

endTransaction 关闭事务,如果未提交事务,则自动rollback

db.beginTransaction(); //开始事务try {…… //这里填写数据库操作代码db.setTransactionSuccessful();  //提交事务} finally {db.endTransaction(); //关闭事务}

数据绑定的必要性

数据绑定是指将界面和数据进行绑定,在界面和数据之间建立绑定模式有助于数据的呈现

Adapter其实就是界面和数据之间绑定的桥梁,将视图和数据绑定后将会降低维护数据的复杂度

SimpleCursorAdapter提供了数据层的数据绑定桥梁

SimpleCursorAdapter可以将数据库层的数据提供给列表

1、准备一个列表项的布局用于ListView的展现

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal" ><TextView android:id="@+id/nametextview“ android:layout_width="0dp“android:layout_height="40dp“ android:layout_weight="1"/><TextView android:id="@+id/agetextview“ android:layout_width="80dp"android:layout_height="40dp"/></LinearLayout>

SimpleCursorAdapter可以将数据库层的数据提供给列表

2、使用SimpleCursorAdapter展现数据 

ListView bookListView = (ListView)findViewById(R.id.booklist);String [] from = new String[] { "_name", "_age“ };int [] to = new int[] { R.id.nametextview, R.id.agetextview };Cursor cursor = db.rawQuery(“select * from books”, null);SimpleCursorAdapter adapter = new         SimpleCursorAdapter(MainActivity.this,                 R.layout.book_list_item, cursor, from, to, 0);bookListView.setAdapter(adapter);

修改绑定数据

有时候直接展现的数据可能不符合要求,需要转变后展示,可以通过SimpleCursorAdapter.ViewBinder接口来实现

修改的步骤如下:

1、编写一个类实现SimpleCursorAdapter.ViewBinder接口

SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() {public boolean setViewValue(View view, Cursor cursor, int columnIndex) {if(cursor.getColumnIndex("_name") == columnIndex) {TextView v = (TextView)view;v.setText("N:" + cursor.getString(columnIndex));return true;}return false;}};

修改绑定数据

修改的步骤如下:

2、使用ViewBinder修改数据

ListView bookListView = (ListView)findViewById(R.id.booklist);String [] from = new String[] { "_name", "_age“ };int [] to = new int[] { R.id.nametextview, R.id.agetextview };Cursor cursor = db.rawQuery(“select * from books”, null);SimpleCursorAdapter adapter = new         SimpleCursorAdapter(MainActivity.this,                 R.layout.book_list_item, cursor, from, to, 0);adapter.setViewBinder(viewBinder);bookListView.setAdapter(adapter);

Android SQLite3 数据库操作

Android SQLite3 数据库操作

Android 使用 SQLite数据库一般操作有:创建数据库、创建表、打开数据库、添加数据、删除数据、修改数据、查询数据、关闭数据库。

1.建立一个DatabaseUtil类:

其中内嵌一个DatabaseHelper类继承SQLiteOpenHelper。SQLiteOpenHelper需要实现两个方法onCreate(SQLiteDatabase)用于创建数据库,onUpgrade(SQLiteDatabase,int,int)升级数据库。

SQLiteDatabase,用来管理数据库,它提供了insert、delete、query等方法。

2.创建数据库,创建表:

private static final String CREATE_DATA_NAME = "create table  LatLon (id long primary key, start_time timestamp not null, end_time timestamp not null, interval long not null, start_x integer, start_y integer, min_x integer, min_y integer, max_x integer, max_y integer,history varchar(100))"; 
/**
     * 创建更新数据库
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        /**
         * 创建
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.i(TAG, "Creating DataBase: " + CREATE_DATA_NAME);
            db.execSQL(CREATE_DATA_NAME);
        }

        /**
         * 数据库版本变化时调用
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);
        }
    }

这样就创建了一个数据库,表名为LatLon,字段有id , start_time , end_time , interval , start_x , start_y , min_x , min_y , max_x , max_y , history

3.打开数据库:

public DatabaseUtil(Context ctx) {
        this.mCtx = ctx;
    }
/**
     * 打开数据库
     */
    public DatabaseUtil open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

调用时:

DatabaseUtil dbUtil = new DatabaseUtil(getApplicationContext());
dbUtil.open();

4.添加数据:

DBUtil中insert方法:

/**
 * 添加数据
 */
    public long insert(long time, long start_time, long end_time, long interval, double start_x,
            double start_y, double min_x, double min_y, double max_x, double max_y, String history) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("id", time);
        initialValues.put("start_time", start_time);
        initialValues.put("end_time", end_time);
        initialValues.put("interval", interval);
        initialValues.put("start_x", start_x);
        initialValues.put("start_y", start_y);
        initialValues.put("min_x", min_x);
        initialValues.put("min_y", min_y);
        initialValues.put("max_x", max_x);
        initialValues.put("max_y", max_y);
        initialValues.put("history", history);
        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

调用方法时:

public void recordLocation(Location loc) {

        DatabaseUtil dbUtil = new DatabaseUtil(getApplicationContext());
        dbUtil.open();
        dbUtil.insert(System.currentTimeMillis(), 
                      System.currentTimeMillis(),
                      System.currentTimeMillis(),
                      5, loc.getLongitude(), 
                      loc.getAltitude(),
                      loc.getLongitude(), 
                      loc.getAltitude(),
                      loc.getLongitude(), 
                      loc.getAltitude(),
                      "[asdf{sdf:sdf,sdf}]");
        dbUtil.close();

    }
这样就可以将需要的值存入数据库。

5.删除数据:

删除某一行的数据:

/**
 * 根据时间删除数据
 * 
 */
    public boolean deleteBytime(long time) {
        return mDb.delete(DATABASE_TABLE, "id" + "=" + time, null) > 0;
    }

调用方法时:

DatabaseUtil dbUtil = new DatabaseUtil(getApplicationContext());
dbUtil.open();
dbUtil.deleteBytime(1359363721903L);
dbUtil.close();

6.修改数据:

暂无修改数据需求。

如有需求:

利用ContentValues 更新数据

mDb.update(表名,ContentValues,条件,null);

方法返回值为int类型。

7.查询数据:

查询出所有数据,返回的是一个Cursor:

/**
     * 查询所有数据
     * 
     * @return Cursor
     */
    public Cursor queryAll() {
        return mDb.query(DATABASE_TABLE, new String[] { "id", "start_time", "end_time", "interval",
                "start_x", "start_y", "min_x", "min_y", "max_x", "max_y", "history" }, null, null,
                null, null, null);
    }

调用方法时:

DatabaseUtil dbUtil = new DatabaseUtil(getApplicationContext());
        dbUtil.open();
        Cursor cursor = dbUtil.queryAll();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                     System.out.println(cursor.getInt(0) + "   " + cursor.getDouble(2) + "  "
                        + cursor.getDouble(1));
            }
        }
        dbUtil.close();

8.关闭数据库:

关闭数据库方法:

/**
     * 关闭数据库
     */
    public void close() {
        mDbHelper.close();
    }


调用方法时:

dbUtil.close();

Android Sqlite数据库中基础的增删改查操作

Android Sqlite数据库中基础的增删改查操作

1.创建一个类MyUserlogDBHelper去继承sqliteOpenHelper,在该类里面创建表。

package com.example.demo;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;

import androidx.annotation.Nullable;

public class MyUserlogDBHelper extends sqliteOpenHelper {

    public MyUserlogDBHelper db;
    //对外提供参数,单例模式
    private static sqliteOpenHelper mHelper;
    public static synchronized sqliteOpenHelper getInstance(Context context){
        if (mHelper==null){
            mHelper=new MyUserlogDBHelper(context,"user_log",null,1);
        }
        return mHelper;
    }

    private MyUserlogDBHelper(@Nullable Context context, @Nullable String name, @Nullable sqliteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(sqliteDatabase db) {
        //创建表
        String sql="create table user_log (_id integer primary key autoincrement,name text)";
        //拿到db执行sql语句即可
        db.execsql(sql);
    }

    @Override
    public void onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) {

    }
}

2.在Activity中写查询,增加,修改,删除数据的操作。

package com.example.demo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void create(View view) {
        sqliteOpenHelper helper = MyUserlogDBHelper.getInstance(this);
        sqliteDatabase readableDatabase = helper.getReadableDatabase();
    }
    //查询语句
    public void query(View view) {
        sqliteOpenHelper instance = MyUserlogDBHelper.getInstance(this);
        sqliteDatabase db = instance.getReadableDatabase();

        if (db.isopen()){
            //查询语句
            String sql="select * from user_log";
            //获取游标
            Cursor cursor = db.rawQuery(sql, null);
            while(cursor.movetoNext()){
                //不规范的写法
                /*int _id=cursor.getColumnIndex("0");
                int name=cursor.getColumnIndex("1");
                */
                //规范的写法
                int _id=cursor.getInt(cursor.getColumnIndex("_id"));
    	        String name=cursor.getString(cursor.getColumnIndex("name"));

                Log.d("数据库", "_id: "+_id+",name:"+name);
            }

            //关闭游标
            cursor.close();
            //关闭数据库
            db.close();
        }
    }

    //插入语句
    public void insert(View view) {
        sqliteOpenHelper instance = MyUserlogDBHelper.getInstance(this);
        sqliteDatabase db = instance.getWritableDatabase();

        //判断数据库是否开启
        if (db.isopen()){
            String sql="insert into user_log(name) values('路宇')";

            db.execsql(sql);
        }
        db.close();
    }

    //修改
    public void update(View view) {
        sqliteOpenHelper instance = MyUserlogDBHelper.getInstance(this);
        sqliteDatabase db = instance.getWritableDatabase();
        if (db.isopen()){
            String sql="update user_log set name=? where _id=?";
            db.execsql(sql,new Object[]{"成龙","5"});
        }
        //关闭数据库
        db.close();
    }
    //删除数据
    public void delete(View view) {
        sqliteOpenHelper instance = MyUserlogDBHelper.getInstance(this);
        sqliteDatabase db = instance.getWritableDatabase();
        //判断数据是否是打开状态
        if (db.isopen()){
            String sql="delete from user_log where _id=?";
            db.execsql(sql,new Object[]{6});
        }
    }
}

3.布局文件。

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="创建表"
        android:onClick="create" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询"
        android:onClick="query" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="插入"
        android:onClick="insert" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改"
        android:onClick="update" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除"
        android:onClick="delete" />



</LinearLayout>

以上就是sqlite数据库中,最简单的增删改查操作,想深入学习sqlite在项目中的实际应用,请持续关注后面博文!

Android SQLite数据库加密的操作方法

Android SQLite数据库加密的操作方法

一、前言

SQLite是一个轻量级的、跨平台的、开源的嵌入式数据库引擎,也是一个关系型的的使用SQL语句的数据库引擎,
读写效率高、资源消耗总量少、延迟时间少,使其成为移动平台数据库的最佳解决方案(如Android、iOS)
但是Android上自带的SQLite数据库是没有实现加密的,我们可以通过Android Studio直接导出应用创建的数据库文件,然后通过如SQLite Expere Personal 这种可视化工具打开数据库文件进行查看数据库的表结构,以及数据,这就导致存储在SQLite中的数据可以被任何人查看,如果是一些账号密码,或者聊天数据等,那么我们的应用就面临着严重的安全漏洞隐患;

二、数据库加密方法

因为Android自带的SQLite数据库本身是没有实现加密的,那我们如何实现对数据库的加密呢?

(1)对SQLite数据库的数据进行加密

我们可以在程序中对保存到数据库中的数据 进行加密后保存,然后查询数据的时候,对查询的数据进行解密后使用,如果还不希望别人看到数据库的表结构,我们可以对数据库名字,表名,表中的字段名字使用MD5等加密手段加密后再进行操作;
这种方法是可以达到数据库加密的目的的,但是相对来说操作就比较繁琐了

(2)使用SQLCipher对SQLite数据库加密

SQLCipher是基于SQLite基础之上实现了数据库加密的开源库,可以采用第三方的开源框架SQLCipher,SQLCipher是基于原生SQlite数据库进行扩展,实现数据库整体加密(数据库文件加密),提供的数据库的操作接口,和原生的SQLite数据库操作接口基本一样的;我们创建或者打开数据库都需要密码,我们打开数据库时的密码,需要和创建数据库时的密码保护一致,否则打开数据库时会报错,提示打开的文件不是一个数据库文件

net.sqlcipher.database.SQLiteException: file is not a database;

我们导出的数据库文件,通过SQLite Expere Personal这类可视化工具也是无法直接打开的;但是可以使用DB Browser for Sqlite这个数据库查看工具进行查看,查看的时候输入创建数据库时使用的加密密码

SQLCipher的特点:

SQLCipher 占用空间小,性能好,因此非常适合保护嵌入式应用程序数据库,非常适合移动开发。

(1)极快的性能,加密开销低至 5-15%

(2)数据库文件中的数据 100% 已加密,是对所有数据文件,包括数据文件和缓存、结构文件等等进行加密。

(3)使用良好的安全实践(CBC 模式、密钥派生),加密算法是256位 AES 在 CBC 模式

(4)使用 OpenSSL 加密库提供的算法

在Android中集成SQLiteCipher:

-添加SQLiteCipher的依赖

implementation ''net.zetetic:android-database-sqlcipher:4.4.3@aar''
implementation "androidx.sqlite:sqlite:2.0.1"

-使用SQLiteCipher提供的相关接口操作

 SQLiteDatabase.loadLibs(this)
                val databaseFile = getDatabasePath("demo.db")
                if (databaseFile.exists()) databaseFile.delete()
                databaseFile.mkdirs()
                databaseFile.delete()
                val database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123", null)
                database.execSQL(
                    "CREATE TABLE " + DatabaseHelper.TABLE_MUSIC_TYPE + " (type_id integer primary key autoincrement not null," +
                            "type_no integer,type_name text)"
                )
                database.execSQL(
                    "insert into " + DatabaseHelper.TABLE_MUSIC_TYPE + " (type_no,type_name) " +
                            "values (''" + 1 + "'',''" + "送餐音乐" + "'')"
                )

上面的代码在调用时,会创建数据库demo.db,传入了数据库密码,并且创建了一个表music_type,并且向表中插入了一条数据;
注意代码中的数据库相关的操作,都是使用SQLIteCipher中的相关接口即net.sqlcipher.database包名下的相关接口,不要使用成了原生SQLite的相关接口

SQLiteDatabase.loadLibs(this)
                val databaseFile = getDatabasePath("demo.db")
                val database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123", null)
                val cursor = database.rawQuery(
                    "select * from " + DatabaseHelper.TABLE_MUSIC_TYPE,
                    null
                )

                var musicTypeList: MutableList<MusicTypeBean> = mutableListOf();

                while (cursor.moveToNext()) {
                    var musicTypeBean = MusicTypeBean();
                    musicTypeBean.id = cursor.getInt(cursor.getColumnIndex("type_no"))
                    musicTypeBean.name = cursor.getString(cursor.getColumnIndex("type_name"))
                    musicTypeList.add(musicTypeBean)
                }
                cursor.close()
                Log.e(TAG, "onClick: " + musicTypeList.size)

上述代码就是查询demo.db数据库中的music_type表中的数据,获取数据库对象的时候,注意传入的密码和创建数据库时要保持一致;

上面使用SQLiteCipher创建数据库和表,以及向表中插入数据,查询表中的数据,除了创建数据库获取可读写数据库对象和原生SQLite API有些区别一样,其他执行SQL语句,查询表中数据的API 和原生 SQlite API是完全一样的;

SQLiteCipher结合Room框架使用

我们知道在使用SQLite数据库的时候,我们往往会使用一些比较方便的ORM(对象关系映射)框架来帮助我们操作数据库,如GreenDAO,Room(Jetpack组件)等,那如何将SQLiteCipher结合这些ORM框架使用;我们这里介绍一下Google Jetpack组件中的ORM框架 Room结合SQLiteCipher使用;

其实Room结合SQLiteCipher使用,就是在创建数据库时候,需要先创建一个SupportFactory
,SupportFactory中会传入通过SQLiteCipher中的SQLiteDatabase获取的密码字节数据

  SQLiteDatabase.loadLibs(this)
                val passphrase = SQLiteDatabase.getBytes("test123".toCharArray())
                val factory = SupportFactory(passphrase, object : SQLiteDatabaseHook {
                    override fun preKey(database: SQLiteDatabase?) {
                        LogUtil.e(TAG, "preKey")
                    }

                    override fun postKey(database: SQLiteDatabase?) {
                        LogUtil.e(TAG, "postKey")
                    }
                }, true)

然后在创建数据库的时候,通过Room自带的openHelperFactory()方法传入创建的SupportFactory即可,这样就能创建加密数据库了;其他操作,就按照Room正常的操作即可

var mInstance= Room
                   .databaseBuilder(
                            context.applicationContext,
                            AppDatabase::class.java,
                            DB_NAME
                        ).addCallback(object : RoomDatabase.Callback() {
                            override fun onCreate(db: SupportSQLiteDatabase) {
                                super.onCreate(db)
                                Log.e(TAG, "onCreate: ")
                                initMusicTypeData(context, db)
                            }
                        }).openHelperFactory(factory)
                        .build()

查看并导出加密数据库文件

-导出数据库文件

我们手机通过USB连接电脑之后,打开开发者模式,然后在Android Studio菜单栏中的View->
Tool Windows->Device File Explorer

然后在Device File Explorer中进入 data/data/应用包名/databases中找到我们创建的数据库文件demo.db,然后我们可以右键改文件Save As 导出该数据库文件

在这里插入图片描述
-查看加密数据库文件

前面我们已经提到过,可以通过DB Browser for SQLite来查看加密的数据库文件
下载地址:https://sqlitebrowser.org/dl/

下载安装之后,我们打开安装目录下的DB Browser for SQLCipher.exe程序,然后通过菜单栏中的文件->打开数据库->打开导出的加密数据库文件,然后输入数据库文件的加密密码,就是我们在程序中SQLiteCipher加密数据库文件时使用的密码,输入正确密码后,可以正常打开数据库文件

在这里插入图片描述

在这里插入图片描述
右键表名,选择浏览数据,即可查看表中的数据

在这里插入图片描述

到此这篇关于Android SQLite数据库加密的操作方法的文章就介绍到这了,更多相关Android SQLite数据库加密内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • Android实现点击图片上传SQLite数据库
  • Android 通过SQLite数据库实现数据存储管理
  • Android SQLite数据库连接实现登录功能
  • Android Studio连接SQLite数据库的登录注册实现
  • Android中SQLite数据库知识点总结
  • Android SQLite数据库进行查询优化的方法
  • Android SharePreferences与数据库SQLite存储实现方法介绍

Android SQLite数据库操作代码类分享

Android SQLite数据库操作代码类分享

使用示例:

package cn.hackcoder.beautyreader.db;

import android.content.Context;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;
import android.util.Log;

/**
 * Created by hackcoder on 15-1-25.
 */
public class DataBaseHelper extends sqliteOpenHelper {
  private static final String dbname = "sample.db";
  private static int dbVersion = 1;

  public DataBaseHelper(Context context) {
    super(context,dbname,null,dbVersion);
  }

  @Override
  public void onCreate(sqliteDatabase db) {
    Log.d("===========","数据库初始化");
    //建表
    String sql = "create table if not exists tb_article(id integer primary key autoincrement,title varchar(50),content TEXT,url varchar(50),page integer)";
    db.execsql(sql);
  }

  /**
   *
   * @param db
   * @param oldVersion
   * @param newVersion
   */
  @Override
  public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {

  }
}

类源码:

package cn.hackcoder.beautyreader.service;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.sqliteDatabase;

import java.util.ArrayList;
import java.util.List;

import cn.hackcoder.beautyreader.db.DataBaseHelper;
import cn.hackcoder.beautyreader.model.Article;

/**
 * Created by hackcoder on 15-1-25.
 */
public class ArticleService {

  private DataBaseHelper dataBaseHelper;
  private sqliteDatabase readableDatabase;
  private sqliteDatabase writableDatabase;

  public ArticleService(Context context) {
    dataBaseHelper = new DataBaseHelper(context);
  }

  public void add(Article article) {
    String sql = "insert into tb_article(id,title,content,url,page) values(?,?,?)";
    getReadableDatabase().execsql(sql,new Object[]{null,article.getTitle(),article.getContent(),article.getUrl(),article.getPage()});
  }

  public void delete(int id) {
    String sql = "delete from tb_article where id =?";
    getReadableDatabase().execsql(sql,new Object[]{id});
  }

  public void deleteall() {
    String sql = "delete from tb_article";
    getReadableDatabase().execsql(sql,null);
  }
  public void update(Article article) {
    String sql = "update tb_article set title=?,content=?,url=?,page = ? where id =?";
    getReadableDatabase().execsql(sql,new Object[]{article.getTitle(),article.getPage(),article.getId()});
  }

  public void updateContentOfUrl(String url,String content){
    String sql = "update tb_article set content=? where url =?";
    getReadableDatabase().execsql(sql,new Object[]{content,url});
  }
  public Article find(int id) {
    Article article = new Article();
    String sql = "select id,page from tb_article where id = ?";
    Cursor cursor = getReadableDatabase().rawQuery(sql,new String[]{String.valueOf(id)});
    if (cursor.movetoNext()) {
      article.setId(id);
      article.setTitle(cursor.getString(cursor.getColumnIndex("title")));
      article.setContent(cursor.getString(cursor.getColumnIndex("content")));
      article.setUrl(cursor.getString(cursor.getColumnIndex("url")));
      article.setPage(cursor.getInt(cursor.getColumnIndex("page")));
      cursor.close();
      return article;
    }
    cursor.close();
    return null;
  }

  public List<Article> findByUrl(String url) {
    List<Article> articles = new ArrayList<Article>();
    String sql = "select id,page from tb_article where url = ?";
    Cursor cursor = getReadableDatabase().rawQuery(sql,new String[]{url});
    while (cursor.movetoNext()) {
      Article article = new Article();
      article.setId(cursor.getInt(cursor.getColumnIndex("id")));
      article.setTitle(cursor.getString(cursor.getColumnIndex("title")));
      article.setContent(cursor.getString(cursor.getColumnIndex("content")));
      article.setUrl(cursor.getString(cursor.getColumnIndex("url")));
      article.setPage(cursor.getInt(cursor.getColumnIndex("page")));
      articles.add(article);
    }
    cursor.close();
    return articles;
  }
  public int getCountOfPage(int page){
    String sql = "select count(*) from tb_article where page = ?";
    Cursor cursor = getReadableDatabase().rawQuery(sql,new String[]{String.valueOf(page)});
    cursor.movetoFirst();
    int count = cursor.getInt(0);
    cursor.close();
    return count;
  }

  public List<Article> getArticlesOfPage(int curPage){
    List<Article> articles = new ArrayList<Article>();
    String sql = "select id,page from tb_article where page = ?";
    Cursor cursor = getReadableDatabase().rawQuery(sql,new String[]{String.valueOf(curPage)});
    while(cursor.movetoNext()){
      Article article = new Article();
      article.setId(cursor.getInt(cursor.getColumnIndex("id")));
      article.setTitle(cursor.getString(cursor.getColumnIndex("title")));
      article.setContent(cursor.getString(cursor.getColumnIndex("content")));
      article.setUrl(cursor.getString(cursor.getColumnIndex("url")));
      article.setPage(cursor.getInt(cursor.getColumnIndex("page")));
      articles.add(article);
    }
    cursor.close();
    return articles;
  }
  public int countOfSum() {
    String sql = "select count(*) from tb_article";
    Cursor cursor = getReadableDatabase().rawQuery(sql,null);
    cursor.movetoFirst();
    int count = cursor.getInt(0);
    cursor.close();
    return count;
  }

  public List<Article> getArticles(int start,int pageSize) {
    List<Article> articles = new ArrayList<Article>();
    String sql = "select id,page from tb_article limit ?,?";
    Cursor cursor = getReadableDatabase().rawQuery(sql,new String[]{String.valueOf(start),String.valueOf(pageSize)});
    while(cursor.movetoNext()){
      Article article = new Article();
      article.setId(cursor.getInt(cursor.getColumnIndex("id")));
      article.setTitle(cursor.getString(cursor.getColumnIndex("title")));
      article.setContent(cursor.getString(cursor.getColumnIndex("content")));
      article.setUrl(cursor.getString(cursor.getColumnIndex("url")));
      article.setPage(cursor.getInt(cursor.getColumnIndex("page")));
      articles.add(article);
    }
    cursor.close();
    return articles;
  }

  public void closeDB() {
    if (readableDatabase != null && readableDatabase.isopen()) {
      readableDatabase.close();
    }
    if (writableDatabase != null && writableDatabase.isopen()) {
      writableDatabase.close();
    }
  }

  public sqliteDatabase getReadableDatabase() {
    return dataBaseHelper.getReadableDatabase();
  }

  public sqliteDatabase getWritableDatabase() {
    return dataBaseHelper.getWritableDatabase();
  }
}

今天关于跟我学Android之十三 SQLite数据库操作的讲解已经结束,谢谢您的阅读,如果想了解更多关于Android SQLite3 数据库操作、Android Sqlite数据库中基础的增删改查操作、Android SQLite数据库加密的操作方法、Android SQLite数据库操作代码类分享的相关知识,请在本站搜索。

本文标签: