Sqlite数据库使用指南

前言:原生的Sqlite在实际开发中应该会比较少用到,所以会造成一些知识点被冷却。以下是本人在一个项目中用到原生sqlite的一些例子,借鉴了几位前辈的代码,整理而成。若以后用到可以直接拿来稍作修改就行了。
1、DBHelper继承SQLiteOpenHelper

/**
 * @desc
 * @auth 方毅超
 * @time 2017/9/14 15:17
 */

public class DBHelper extends SQLiteOpenHelper {

    //version number to upgrade database version
    //each time if you Add, Edit table, you need to change the
    //version number.
    //每次你对数据表进行编辑,添加时候,你都需要对数据库的版本进行提升

    //数据库版本
    private static final int DATABASE_VERSION=1;

    //数据库名称
    private static final String DATABASE_NAME="csair_ehome.db";


    public DBHelper(Context context){
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建数据表
        db.execSQL(StaffSqlite.CREATE_TABLE_STAFF_MSG);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //如果旧表存在,删除,所以数据将会消失
        db.execSQL("DROP TABLE IF EXISTS "+ StaffSqlite.TABLE);

        //再次创建表
        onCreate(db);
    }
}

2、建表时的相关属性、语句

/**
 * @desc
 * @auth 方毅超
 * @time 2017/9/14 15:31
 */

public class StaffSqlite {
    //表名
    public static final String TABLE = "StaffMsg";
    //表的各个域名
    public static final String KEY_ID = "id";

    public static final String KEY_DATA_ID = "data_Id";
    public static final String KEY_MSG_ID = "msgId";
    public static final String KEY_MSG_TYPE = "msgType";
    public static final String KEY_TITLE = "title";
    public static final String KEY_CONTENT = "content";
    public static final String KEY_URL = "url";
    public static final String KEY_IMAGE_ID = "imageId";
    public static final String KEY_SMALL_IMAGE_ID = "smallImageId";
    public static final String KEY_FLAG = "flag";
    public static final String KEY_LAST_UPDATE_TIME = "lastUpdateTime";

    public static final String CREATE_TABLE_STAFF_MSG = "CREATE TABLE " + TABLE + "("
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
            + KEY_DATA_ID + " INTEGER, "
            + KEY_MSG_ID + " varchar(8), "
            + KEY_MSG_TYPE + " varchar(4), "
            + KEY_TITLE + " varchar(32), "
            + KEY_CONTENT + " TEXT, "
            + KEY_URL + " varchar(128), "
            + KEY_IMAGE_ID + " INTEGER, "
            + KEY_SMALL_IMAGE_ID + " INTEGER, "
            + KEY_FLAG + " varchar(4), "
            + KEY_LAST_UPDATE_TIME + " varchar(32))";



    //    {
//        "id": 1207189,
//            "msgId": "test0",
//            "msgType": "A",
//            "title": "title",
//            "content": "content",
//            "url": "url",
//            "imageId": 1,
//            "smallImageId": 0,
//            "flag": "A",
//            "lastUpdateTime": "2017-09-14 08:54:44"
//    },
    //属性
    private int data_Id;
    private String msgId;
    private String msgType;
    private String title;
    private String content;
    private String url;
    private int imageId;
    private int smallImageId;
    private String flag;
    private String lastUpdateTime;


}

3、增删改查的操作

/**
 * @desc
 * @auth 方毅超
 * @time 2017/9/14 16:37
 */

public class StaffRepo {

    private static class SingletonHolder {
        static final StaffRepo INSTANCE = new StaffRepo();
    }

    public static StaffRepo getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /*数据库助手*/
    private DBHelper dbHelper;

    public StaffRepo init(Context context) {
        if (dbHelper == null) {
            dbHelper = new DBHelper(context);
        }
        return this;
    }


//    public StaffRepo(Context context) {
//        dbHelper = new DBHelper(context);
//    }

    /**
     * 增
     *
     * @param bean
     * @return
     */
    public int insert(StaffMsgBean.DataBean bean) {
        //打开连接,写入数据
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(StaffSqlite.KEY_DATA_ID, bean.getId());
        values.put(StaffSqlite.KEY_MSG_ID, bean.getMsgId());
        values.put(StaffSqlite.KEY_MSG_TYPE, bean.getMsgType());
        values.put(StaffSqlite.KEY_TITLE, bean.getTitle());
        values.put(StaffSqlite.KEY_CONTENT, bean.getContent());
        values.put(StaffSqlite.KEY_URL, bean.getUrl());
        values.put(StaffSqlite.KEY_IMAGE_ID, bean.getImageId());
        values.put(StaffSqlite.KEY_SMALL_IMAGE_ID, bean.getSmallImageId());
        values.put(StaffSqlite.KEY_FLAG, bean.getFlag());
        values.put(StaffSqlite.KEY_LAST_UPDATE_TIME, bean.getLastUpdateTime());

        long id = db.insert(StaffSqlite.TABLE, null, values);
        db.close();
        return (int) id;
    }

    /**
     * 删
     *
     * @param id
     */
    public void delete(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(StaffSqlite.TABLE, StaffSqlite.KEY_DATA_ID + "=?", new String[]{String.valueOf(id)});
        db.close();
    }

    /**
     * 改
     *
     * @param bean
     */
    public void update(StaffMsgBean.DataBean bean) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(StaffSqlite.KEY_DATA_ID, bean.getId());
        values.put(StaffSqlite.KEY_MSG_ID, bean.getMsgId());
        values.put(StaffSqlite.KEY_MSG_TYPE, bean.getMsgType());
        values.put(StaffSqlite.KEY_TITLE, bean.getTitle());
        values.put(StaffSqlite.KEY_CONTENT, bean.getContent());
        values.put(StaffSqlite.KEY_URL, bean.getUrl());
        values.put(StaffSqlite.KEY_IMAGE_ID, bean.getImageId());
        values.put(StaffSqlite.KEY_SMALL_IMAGE_ID, bean.getSmallImageId());
        values.put(StaffSqlite.KEY_FLAG, bean.getFlag());
        values.put(StaffSqlite.KEY_LAST_UPDATE_TIME, bean.getLastUpdateTime());

        db.update(StaffSqlite.TABLE, values, StaffSqlite.KEY_DATA_ID + "=?", new String[]{String.valueOf(StaffSqlite.KEY_DATA_ID)});
        db.close();
    }

    /**
     * 查
     *
     * @param Id
     * @return
     */
    public StaffMsgBean.DataBean getDataById(int Id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery = "SELECT * FROM" + StaffSqlite.TABLE
                + " WHERE " +
                StaffSqlite.KEY_DATA_ID + "=?";
        StaffMsgBean.DataBean data = new StaffMsgBean.DataBean();
        Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(Id)});
        if (cursor.moveToFirst()) {
            do {
                data.setId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_DATA_ID)));
                data.setMsgId(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_MSG_ID)));
                data.setMsgType(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_MSG_TYPE)));
                data.setTitle(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_TITLE)));
                data.setContent(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_CONTENT)));
                data.setUrl(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_URL)));
                data.setImageId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_IMAGE_ID)));
                data.setSmallImageId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_SMALL_IMAGE_ID)));
                data.setFlag(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_FLAG)));
                data.setLastUpdateTime(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_LAST_UPDATE_TIME)));
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return data;
    }

    /**
     * 批量增加
     *
     * @param datas
     * @return
     */
//    public int insertAll(List<StaffMsgBean.DataBean> datas) {
//        //打开连接,写入数据
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        ContentValues values = new ContentValues();
//        long id = 0;
//        for (StaffMsgBean.DataBean bean : datas) {
//            values.put(StaffSqlite.KEY_DATA_ID, bean.getId());
//            values.put(StaffSqlite.KEY_MSG_ID, bean.getMsgId());
//            values.put(StaffSqlite.KEY_MSG_TYPE, bean.getMsgType());
//            values.put(StaffSqlite.KEY_TITLE, bean.getTitle());
//            values.put(StaffSqlite.KEY_CONTENT, bean.getContent());
//            values.put(StaffSqlite.KEY_URL, bean.getUrl());
//            values.put(StaffSqlite.KEY_IMAGE_ID, bean.getImageId());
//            values.put(StaffSqlite.KEY_SMALL_IMAGE_ID, bean.getSmallImageId());
//            values.put(StaffSqlite.KEY_FLAG, bean.getFlag());
//            values.put(StaffSqlite.KEY_LAST_UPDATE_TIME, bean.getLastUpdateTime());
//
//            id = db.insert(StaffSqlite.TABLE, null, values);
//        }
//
//        db.close();
//        return (int) id;
//    }


    /**
     * 批量查询
     *
     * @return
     */
//    public ArrayList<StaffMsgBean.DataBean> getDatasList() {
//        SQLiteDatabase db = dbHelper.getReadableDatabase();
//        String selectQuery = "SELECT * FROM " + StaffSqlite.TABLE;
//        ArrayList<StaffMsgBean.DataBean> msgDatas = new ArrayList<>();
//        Cursor cursor = db.rawQuery(selectQuery, null);
//
//        if (cursor.moveToFirst()) {
//            do {
//                StaffMsgBean.DataBean data = new StaffMsgBean.DataBean();
//                data.setId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_DATA_ID)));
//                data.setMsgId(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_MSG_ID)));
//                data.setMsgType(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_MSG_TYPE)));
//                data.setTitle(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_TITLE)));
//                data.setContent(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_CONTENT)));
//                data.setUrl(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_URL)));
//                data.setImageId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_IMAGE_ID)));
//                data.setSmallImageId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_SMALL_IMAGE_ID)));
//                data.setFlag(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_FLAG)));
//                data.setLastUpdateTime(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_LAST_UPDATE_TIME)));
//                msgDatas.add(data);
//            } while (cursor.moveToNext());
//        }
//        cursor.close();
//        db.close();
//        return msgDatas;
//    }

    /**
     * 分页查询
     *
     * @return
     */
    public ArrayList<StaffMsgBean.DataBean> getDatasList(int pageNow, int pageSize) {
        long count = getDatasCount();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        if (pageNow < 1 || pageSize < 1)
            throw new IllegalArgumentException("pageNow、pageSize必须大于等于1");
        int star = (pageNow - 1) * pageSize;
        String selectQuery = "SELECT * FROM " + StaffSqlite.TABLE
                + " ORDER BY " + StaffSqlite.KEY_DATA_ID
                + " DESC limit " + star + "," + pageSize;    //m开始,取n条

        ArrayList<StaffMsgBean.DataBean> msgDatas = new ArrayList<>();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                StaffMsgBean.DataBean data = new StaffMsgBean.DataBean();
                data.setId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_DATA_ID)));
                data.setMsgId(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_MSG_ID)));
                data.setMsgType(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_MSG_TYPE)));
                data.setTitle(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_TITLE)));
                data.setContent(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_CONTENT)));
                data.setUrl(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_URL)));
                data.setImageId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_IMAGE_ID)));
                data.setSmallImageId(cursor.getInt(cursor.getColumnIndex(StaffSqlite.KEY_SMALL_IMAGE_ID)));
                data.setFlag(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_FLAG)));
                data.setLastUpdateTime(cursor.getString(cursor.getColumnIndex(StaffSqlite.KEY_LAST_UPDATE_TIME)));
                msgDatas.add(data);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return msgDatas;
    }

    /**
     * 查询数据库中的总条数.
     *
     * @return
     */
    private long getDatasCount() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String sql = "SELECT count(*) FROM " + StaffSqlite.TABLE;
        Cursor cursor = db.rawQuery(sql, null);
        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.close();
        db.close();
        return count;
    }

    /**
     * 批量处理消息:状态,A增加,U更新,D删除
     *
     * @param datas
     */
    public void handleDatas(List<StaffMsgBean.DataBean> datas) {
        //打开连接,写入数据
        for (StaffMsgBean.DataBean bean : datas) {
            switch (bean.getFlag()) {
                case "A":
                    insert(bean);
                    break;
                case "U":
                    update(bean);
                    break;
                case "D":
                    delete(bean.getId());
                    break;
                default:
                    break;
            }
        }
    }
}
//实现CRUD

至此,3个核心类完成,简单易懂易用。将其中的数据库名、数据表名、表属性等修改一下就可以用了。

后记:该文少了升级数据库的部分,可以看下一下链接,也是清晰易懂
Android SQLite数据库版本升级的管理实现

    原文作者:方毅超
    原文地址: https://www.jianshu.com/p/66ef14551611
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞