android 一个SQLite数据库多个数据表的基本使用框架 (带demo)

时间:2022-09-09 23:38:32

android 一个SQLite数据库多个数据表(带demo)

前言
        demo演示
        一、搭建
        二、建立实体类
        三、建立数据库操作类
        四、配置Application
        五、使用
    GitHub

前言

我的上一篇博客讲的是简单的 android SQLite 数据库的基本操作如增删改查,有兴趣的朋友可以点一下这里android 简单SQLite数据库 增删改查

但是呢,一般的项目里,一个数据库也不会只有一个数据表,常常是多个数据表共同管理的,这个时候应该怎么搭建项目的数据库操作代码框架呢?

光说不练假把式,动手开一个Demo
demo演示

demo
一、搭建

首先,在项目里建立起三个文件夹,分别是 app 、 db 、 model
文件夹
app 文件夹下存放继承 Application 的 MyApplication 类
db 文件夹下存放 数据库操作类
model 文件夹下存放 数据实体类
二、建立实体类

在 model 文件夹下创建 实体类 PhoneBean

/**
 * 手机实体类
 * @author  dlong
 * created at 2019/3/13 11:34 AM
 */
public class PhoneBean {
    /** 数据库自增ID */
    public int id;
    /** 手机品牌 */
    public String brand;
    /** 手机型号 */
    public String model;
    /** 手机价格 */
    public int price;

/**
     * 转化成字符串
     * @return
     */
    public String toString(){
        StringBuilder builder = new StringBuilder("[");
        builder.append(id).append("--");
        builder.append("品牌:").append(brand).append("--");
        builder.append("型号:").append(model).append("--");
        builder.append("价格:").append(price).append("]");
        return builder.toString();
    }
}

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28

在 model 文件夹下创建 实体类 CompanyBean

/**
 * 公司实体类
 * @author  dlong
 * created at 2019/3/13 11:37 AM
 */
public class CompanyBean {
    /** 数据库自增ID */
    public int id;
    /** 公司名称 */
    public String name;
    /** 公司CEO */
    public String ceo;
    /** 公司建立年份 */
    public int year;

public String toString(){
        StringBuilder builder = new StringBuilder("[");
        builder.append(id).append("--");
        builder.append("公司名称:").append(name).append("--");
        builder.append("CEO:").append(ceo).append("--");
        builder.append("创立年份:").append(year).append("年]");
        return builder.toString();
    }
}

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24

三、建立数据库操作类

在 db 文件夹下建立一个 DBConfig 用于记录数据库配置信息

/**
 * 数据库配置信息
 * @author  dlong
 * created at 2019/3/13 11:27 AM
 */
public class DBConfig {
    /**  数据库名称 */
    public static final String DB_NAME = "multiple_test.db";
    /**  数据库版本 */
    public static final int DB_VERSION = 1;

/**
     * 判断数据表是否为空
     * @param db
     * @param tablename
     * @return
     */
    public static boolean HaveData(SQLiteDatabase db, String tablename){
        Cursor cursor;
        boolean a = false;
        cursor = db.rawQuery("select name from sqlite_master where type='table' ", null);
        while(cursor.moveToNext()){
            //遍历出表名
            String name = cursor.getString(0);
            if(name.equals(tablename)){
                a = true;
            }
            Log.i("System.out", name);
        }
        if(a){
            cursor = db.query(tablename,null,null,null,null,null,null);
            //检查是不是空表
            return cursor.getCount() > 0;
        }else {
            return false;
        }
    }
}

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38

在 db 文件夹下建立一个 PhoneDBDao 用于操作数据表

/**
 * 手机数据表操作类
 * @author  dlong
 * created at 2019/3/13 11:39 AM
 */
public class PhoneDBDao {

/** 数据表名称 */
    public static final String TABLE_NAME = "phone_info";

/** 表的字段名 */
    public static String KEY_ID = "id";
    public static String KEY_BRAND = "brand";
    public static String KEY_MODEL = "model";
    public static String KEY_PRICE = "price";

private SQLiteDatabase mDatabase;
    /** 上下文 */
    private Context mContext;
    /** 数据库打开帮助类 */
    private DBMaster.DBOpenHelper mDbOpenHelper;

public PhoneDBDao(Context context) {
        mContext = context;
    }

public void setDatabase(SQLiteDatabase db){
        mDatabase = db;
    }

/**
     * 插入一条数据
     * @param phone
     * @return
     */
    public long insertData(PhoneBean phone) {
        ContentValues values = new ContentValues();
        values.put(KEY_BRAND, phone.brand);
        values.put(KEY_MODEL, phone.model);
        values.put(KEY_PRICE, phone.price);
        return mDatabase.insert(TABLE_NAME, null, values);
    }

/**
     * 删除一条数据
     * @param id
     * @return
     */
    public long deleteData(int id) {
        return mDatabase.delete(TABLE_NAME, KEY_ID + "=" + id, null);
    }

/**
     * 删除所有数据
     * @return
     */
    public long deleteAllData() {
        return mDatabase.delete(TABLE_NAME, null, null);
    }

/**
     * 更新一条数据
     * @param id
     * @param phone
     * @return
     */
    public long updateData(int id, PhoneBean phone) {
        ContentValues values = new ContentValues();
        values.put(KEY_BRAND, phone.brand);
        values.put(KEY_MODEL, phone.model);
        values.put(KEY_PRICE, phone.price);
        return mDatabase.update(TABLE_NAME, values, KEY_ID + "=" + id, null);
    }

/**
     * 查询一条数据
     * @param id
     * @return
     */
    public List<PhoneBean> queryData(int id) {
        if (!DBConfig.HaveData(mDatabase,TABLE_NAME)){
            return null;
        }
        Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID,
                        KEY_BRAND,
                        KEY_MODEL,
                        KEY_PRICE},
                KEY_ID + "=" + id , null, null, null, null);
        return convertUtil(results);
    }

/**
     * 查询所有数据
     * @return
     */
    public List<PhoneBean> queryDataList() {
        if (!DBConfig.HaveData(mDatabase,TABLE_NAME)){
            return null;
        }
        Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID,
                        KEY_BRAND,
                        KEY_MODEL,
                        KEY_PRICE},
                null, null, null, null, null);
        return convertUtil(results);
    }

/**
     * 查询结果转换
     * @param cursor
     * @return
     */
    private List<PhoneBean> convertUtil(Cursor cursor) {
        int resultCounts = cursor.getCount();
        if (resultCounts == 0 || !cursor.moveToFirst()) {
            return null;
        }
        List<PhoneBean> mList = new ArrayList<>();
        for (int i = 0; i < resultCounts; i++) {
            PhoneBean phone = new PhoneBean();
            phone.id = cursor.getInt(cursor.getColumnIndex(KEY_ID));
            phone.brand = cursor.getString(cursor.getColumnIndex(KEY_BRAND));
            phone.model = cursor.getString(cursor.getColumnIndex(KEY_MODEL));
            phone.price = cursor.getInt(cursor.getColumnIndex(KEY_PRICE));
            mList.add(phone);
            cursor.moveToNext();
        }
        return mList;
    }
}

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130

在 db 文件夹下建立一个 CompanyDBDao 用于操作数据表

/**
 * 公司数据表操作类
 * @author  dlong
 * created at 2019/3/13 11:46 AM
 */
public class CompanyDBDao {

/** 数据表名称 */
    public static final String TABLE_NAME = "company_info";

/** 表的字段名 */
    public static String KEY_ID = "id";
    public static String KEY_NAME = "name";
    public static String KEY_CEO = "ceo";
    public static String KEY_YEAR = "year";

private SQLiteDatabase mDatabase;
    /** 上下文 */
    private Context mContext;
    /** 数据库打开帮助类 */
    private DBMaster.DBOpenHelper mDbOpenHelper;

public CompanyDBDao(Context context) {
        mContext = context;
    }

public void setDatabase(SQLiteDatabase db){
        mDatabase = db;
    }

/**
     * 插入一条数据
     * @param company
     * @return
     */
    public long insertData(CompanyBean company) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, company.name);
        values.put(KEY_CEO, company.ceo);
        values.put(KEY_YEAR, company.year);
        return mDatabase.insert(TABLE_NAME, null, values);
    }

/**
     * 删除一条数据
     * @param id
     * @return
     */
    public long deleteData(int id) {
        return mDatabase.delete(TABLE_NAME, KEY_ID + "=" + id, null);
    }

/**
     * 删除所有数据
     * @return
     */
    public long deleteAllData() {
        return mDatabase.delete(TABLE_NAME, null, null);
    }

/**
     * 更新一条数据
     * @param id
     * @param company
     * @return
     */
    public long updateData(int id, CompanyBean company) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, company.name);
        values.put(KEY_CEO, company.ceo);
        values.put(KEY_YEAR, company.year);
        return mDatabase.update(TABLE_NAME, values, KEY_ID + "=" + id, null);
    }

/**
     * 查询一条数据
     * @param id
     * @return
     */
    public List<CompanyBean> queryData(int id) {
        if (!DBConfig.HaveData(mDatabase,TABLE_NAME)){
            return null;
        }
        Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID,
                        KEY_NAME,
                        KEY_CEO,
                        KEY_YEAR},
                KEY_ID + "=" + id , null, null, null, null);
        return convertUtil(results);
    }

/**
     * 查询所有数据
     * @return
     */
    public List<CompanyBean> queryDataList() {
        if (!DBConfig.HaveData(mDatabase,TABLE_NAME)){
            return null;
        }
        Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID,
                        KEY_NAME,
                        KEY_CEO,
                        KEY_YEAR},
                null, null, null, null, null);
        return convertUtil(results);
    }

/**
     * 查询结果转换
     * @param cursor
     * @return
     */
    private List<CompanyBean> convertUtil(Cursor cursor) {
        int resultCounts = cursor.getCount();
        if (resultCounts == 0 || !cursor.moveToFirst()) {
            return null;
        }
        List<CompanyBean> mList = new ArrayList<>();
        for (int i = 0; i < resultCounts; i++) {
            CompanyBean company = new CompanyBean();
            company.id = cursor.getInt(cursor.getColumnIndex(KEY_ID));
            company.name = cursor.getString(cursor.getColumnIndex(KEY_NAME));
            company.ceo = cursor.getString(cursor.getColumnIndex(KEY_CEO));
            company.year = cursor.getInt(cursor.getColumnIndex(KEY_YEAR));
            mList.add(company);
            cursor.moveToNext();
        }
        return mList;
    }
}

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130

在 db 文件夹下建立一个 DBMaster 用于管理数据库里的全部数据表

/**
 * 数据库总操作类
 * @author  dlong
 * created at 2019/3/13 11:29 AM
 */
public class DBMaster {

/** 上下文 */
    private Context mContext;
    private SQLiteDatabase mDatabase;
    private DBOpenHelper mDbOpenHelper;

/** 数据表操作类实例化 */
    public PhoneDBDao mPhoneDBDao;
    public CompanyDBDao mCompanyDBDao;

public DBMaster(Context context){
        mContext = context;
        mPhoneDBDao = new PhoneDBDao(mContext);
        mCompanyDBDao = new CompanyDBDao(mContext);
    }

/**
     * 打开数据库
     */
    public void openDataBase() {
        mDbOpenHelper = new DBOpenHelper(mContext, DB_NAME, null, DB_VERSION);
        try {
            mDatabase = mDbOpenHelper.getWritableDatabase();//获取可写数据库
        } catch (SQLException e) {
            mDatabase = mDbOpenHelper.getReadableDatabase();//获取只读数据库
        }
        // 设置数据库的SQLiteDatabase
        mPhoneDBDao.setDatabase(mDatabase);
        mCompanyDBDao.setDatabase(mDatabase);
    }

/**
     * 关闭数据库
     */
    public void closeDataBase() {
        if (mDatabase != null) {
            mDatabase.close();
        }
    }

/** 创建该数据库下phone表的语句 */
    private static final String mPhoneSqlStr = "create table if not exists " + PhoneDBDao.TABLE_NAME + " (" +
            PhoneDBDao.KEY_ID + " integer primary key autoincrement , " +
            PhoneDBDao.KEY_BRAND + " text not null , " +
            PhoneDBDao.KEY_MODEL + " text not null , " +
            PhoneDBDao.KEY_PRICE + " integer );";

/** 创建该数据库下Company表的语句 */
    private static final String mCompanySqlStr = "create table if not exists " + CompanyDBDao.TABLE_NAME + " (" +
            CompanyDBDao.KEY_ID + " integer primary key autoincrement , " +
            CompanyDBDao.KEY_NAME + " text not null , " +
            CompanyDBDao.KEY_CEO + " text not null , " +
            CompanyDBDao.KEY_YEAR + " integer );";

/** 删除该数据库下phone表的语句 */
    private static final String mPhoneDelSql = "DROP TABLE IF EXISTS " + PhoneDBDao.TABLE_NAME;

/** 删除该数据库下Company表的语句 */
    private static final String mCompanyDelSql = "DROP TABLE IF EXISTS " + CompanyDBDao.TABLE_NAME;

/**
     * 数据表打开帮助类
     */
    public static class DBOpenHelper extends SQLiteOpenHelper {

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

@Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(mPhoneSqlStr);
            db.execSQL(mCompanySqlStr);
        }

@Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL(mPhoneDelSql);
            db.execSQL(mCompanyDelSql);
            onCreate(db);
        }
    }
}

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89

四、配置Application

在 app 文件夹建立 MyApplication

public class MyApplication extends Application {

/** 声明数据库操作实例 */
    public static DBMaster mDBMaster;

@Override
    public void onCreate() {
        super.onCreate();
        //启动数据库
        mDBMaster = new DBMaster(getApplicationContext());
        mDBMaster.openDataBase();
    }
}

1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

还要在 AndroidManifest.xml 的 <application 里添加

android:name=".app.MyApplication"

1

五、使用

// 新实例化一个PHONE
        PhoneBean phone = new PhoneBean();
        phone.brand = "Google";
        phone.model = "Pixel 3";
        phone.price = 4999;
        // 插入数据库
        MyApplication.mDBMaster.mPhoneDBDao.insertData(phone);

1
    2
    3
    4
    5
    6
    7

// 删除最老的一个数据
        if (null != mPhoneList && mPhoneList.size()>0){
            MyApplication.mDBMaster.mPhoneDBDao.deleteData(mPhoneList.get(0).id);
            updatePhoneTxt();
        }

1
    2
    3
    4
    5

// 查询数据库里的所有数据
        mPhoneList = MyApplication.mDBMaster.mPhoneDBDao.queryDataList();
        // 数据为空,也不能让列表为null
        if (null == mPhoneList) mPhoneList = new ArrayList<>();
---------------------
作者:YD-10-NG
来源:CSDN
原文:https://blog.csdn.net/sinat_38184748/article/details/88532631
版权声明:本文为博主原创文章,转载请附上博文链接!

android 一个SQLite数据库多个数据表的基本使用框架 (带demo)的更多相关文章

  1. Android 学习笔记之如何使用SQLite数据库来保存数据&period;&period;&period;

    PS:最近一阵子都在为考试复习...坑爹的计算机网络,复习了3天,最后该不会的还是不会...明天还考英语...真蛋疼... 学习内容: 1.使用SQLite数据库来保存数据... SQLite:   ...

  2. android中sqlite数据库的基本使用和添加多张表

    看了很多关于android使用sqlite数据库的文章,很多都是介绍了数据库的建立和表的建立,而表通常都是只建立一张,而实际情况我们用到的表可能不止一张,那这种情况下我们又该怎么办呢,好了,下面我教大 ...

  3. Android实现SQLite数据库联系人列表

    Android实现SQLite数据库联系人列表 开发工具:Andorid Studio 1.3 运行环境:Android 4.4 KitKat 工程内容 实现一个通讯录查看程序: 要求使用SQLite ...

  4. Android开发 ---SQLite数据库,lock文件,结果集游标,适配器,安全退出,给连接设置下划线,编辑器,投影,ContentValues存储,DbHelper&comma;activity栈

    目录截图: 1.activity_main.xml 主界面效果: <?xml version="1.0" encoding="utf-8"?> &l ...

  5. Android中SQLite数据库操作(1)——使用SQL语句操作SQLite数据库

    下面是最原始的方法,用SQL语句操作数据库.后面的"Android中SQLite数据库操作(2)--SQLiteOpenHelper类"将介绍一种常用的android封装操作SQL ...

  6. 创建一个 SQLite 数据库

    首先,我们学习如何创建一个SQLite 数据库.如果想要在data/example.sqlite 这个路径中创建一个示例数据库,就必须确保该路径存在.如果该路径不存在,就必须先创建路径:if (!di ...

  7. 孤荷凌寒自学python第四十九天继续研究跨不同类型数据库的通用数据表操作函数

    孤荷凌寒自学python第四十九天继续研究跨不同类型数据库的通用数据表操作函数 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天继续建构自感觉用起来顺手些的自定义模块和类的代码. 不同类型 ...

  8. 孤荷凌寒自学python第四十八天通用同一数据库中复制数据表函数最终完成

    孤荷凌寒自学python第四十八天通用同一数据库中复制数据表函数最终完成 (完整学习过程屏幕记录视频地址在文末) 今天继续建构自感觉用起来顺手些的自定义模块和类的代码. 今天经过反复折腾,最终基本上算 ...

  9. 孤荷凌寒自学python第四十七天通用跨数据库同一数据库中复制数据表函数

    孤荷凌寒自学python第四十七天通用跨数据库同一数据库中复制数据表函数 (完整学习过程屏幕记录视频地址在文末) 今天继续建构自感觉用起来顺手些的自定义模块和类的代码. 今天打算完成的是通用的(至少目 ...

随机推荐

  1. 利用SSH传输文件

    在linux下一般用scp这个命令来通过ssh传输文件. 1.从服务器上下载文件scp username@servername:/path/filename /var/www/local_dir(本地 ...

  2. 理解 Storm 拓扑的并行度&lpar;parallelism&rpar;概念

    组成:一个运行中的拓扑是由什么构成的:工作进程(worker processes),执行器(executors)和任务(tasks)! 在一个 Storm 集群中,Storm 主要通过以下三个部件来运 ...

  3. tomcat 设置虚拟路径的4种方法

    通常使用方法1或者方法2  方法1 (添加配置文件):推荐使用,不需要重启服务器 在Tomcat根目录下的/conf/Catalina/localhost/ 路径下新建一个filename.xml,并 ...

  4. pip问题

    “ModuleNotFoundError: No module named 'pip'”的解决方法:http://www.pianshen.com/article/476461202/ pip错误 I ...

  5. vue中子组件通过&dollar;parent操作父组件的参数或者方法

    先看一个简单的demo: 父组件添加一个弹框,弹框的内容是另外导入的一个子组件: <Modal v-model="accountDetailsModal" class=&qu ...

  6. 如果此表在它的 ChildRelation 集合中不是父表,则不能将关系添加到该集合中。

    今天遇到这个问题头都大了,百度上也没找到解决方案,就自己在哪里沉思................ 终于皇天不负有心人,被我解决了! 这是调用ChildRelations.Add(“名字”,“父级”, ...

  7. jq 便捷api jq 常用 api jq 快捷 api

    jq  选择器 1.相对值用法  width("+=250px") $("input").width("+=250px"); 2.使用函数来 ...

  8. MVPArms MVP快速集成框架

    前言 今年的Android技术圈中MVP,Dagger2,Rxjava,Retrofit这些词汇非常火,随便打开一个技术论坛都充斥着大量的关于这些技术的文章,Github也充斥着各种以基于MVP+Re ...

  9. python爬虫 爬取steam热销游戏

    好久没更新了啊...最近超忙 这学期学了学python 感觉很有趣 就写着玩~~~ 爬取的页面是:https://store.steampowered.com/search/?filter=globa ...

  10. rosbag使用--记录深度相机数据

    首先看一下教程: http://wiki.ros.org/openni_launch/Tutorials/BagRecordingPlayback 知道了rosbag如何进行使用记录深度数据 但是按照 ...