一个封装类教你学会SQLite数据库

Posted pengkv

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个封装类教你学会SQLite数据库相关的知识,希望对你有一定的参考价值。

数据库操作类的命名一般以Dao为结尾,什么是Dao呢?

DAO(Data Access Object) 数据访问对象是第一个面向对象的数据库接口

数据实体类

public class Tree {
    private int id;
    private String name;
    private int age;
    private float price;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public Tree() {
    }

    public Tree(String name, int age, float price) {
        this.name = name;
        this.age = age;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Tree{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ", price=" + price +
                ‘}‘;
    }
}

数据库操作封装类

public class TreeDBDao {

    private static final String DB_NAME = "tree.db";//数据库名称
    private static final String TABLE_NAME = "treeinfo";//数据表名称
    private static final int DB_VERSION = 1;//数据库版本

    //表的字段名
    private static String KEY_ID = "id";
    private static String KEY_NAME = "name";
    private static String KEY_AGE = "age";
    private static String KEY_PRICE = "price";

    private SQLiteDatabase mDatabase;
    private Context mContext;
    private TreeDBOpenHelper mDbOpenHelper;//数据库打开帮助类


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

    //打开数据库
    public void openDataBase() {
        mDbOpenHelper = new TreeDBOpenHelper(mContext, DB_NAME, null, DB_VERSION);
        try {
            mDatabase = mDbOpenHelper.getWritableDatabase();//获取可写数据库
        } catch (SQLException e) {
            mDatabase = mDbOpenHelper.getReadableDatabase();//获取只读数据库
        }
    }

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

    //插入一条数据
    public long insertData(Tree tree) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, tree.getName());
        values.put(KEY_AGE, tree.getAge());
        values.put(KEY_PRICE, tree.getPrice());
        return mDatabase.insert(TABLE_NAME, null, values);
    }

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

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

    //更新一条数据
    public long updateData(long id, Tree tree) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, tree.getName());
        values.put(KEY_AGE, tree.getAge());
        values.put(KEY_PRICE, tree.getPrice());
        return mDatabase.update(TABLE_NAME, values, KEY_ID + "=" + id, null);
    }

    //查询一条数据
    public List<Tree> queryData(long id) {
        Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_AGE, KEY_PRICE},
                KEY_ID + "=" + id, null, null, null, null);
        return convertToTree(results);
    }

    //查询所有数据
    public List<Tree> queryDataList() {
        Cursor results = mDatabase.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_AGE, KEY_PRICE},
                null, null, null, null, null);
        return convertToTree(results);

    }

    private List<Tree> convertToTree(Cursor cursor) {
        int resultCounts = cursor.getCount();
        if (resultCounts == 0 || !cursor.moveToFirst()) {
            return null;
        }
        List<Tree> mTreeList = new ArrayList<>();
        for (int i = 0; i < resultCounts; i++) {
            Tree tree = new Tree();
            tree.setId(cursor.getInt(0));
            tree.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
            tree.setAge(cursor.getInt(cursor.getColumnIndex(KEY_AGE)));
            tree.setPrice(cursor.getFloat(cursor.getColumnIndex(KEY_PRICE)));
            mTreeList.add(tree);
            cursor.moveToNext();
        }
        return mTreeList;
    }

    /**
     * 数据表打开帮助类
     */
    private static class TreeDBOpenHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {
            final String sqlStr = "create table if not exists " + TABLE_NAME + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME + " text not null, " + KEY_AGE + " integer," + KEY_PRICE + " float);";
            db.execSQL(sqlStr);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            final String sqlStr = "DROP TABLE IF EXISTS " + TABLE_NAME;
            db.execSQL(sqlStr);
            onCreate(db);
        }
    }
}

使用方法

TreeDBDao mDBDao = new TreeDBDao(MainActivity.this);//实例化对象
mDBDao.openDataBase();//打开数据库

//增删改查操作

mDBDao.insertData(new Tree("GreenTree", 12, 2321.5f));//增加数据
mDBDao.deleteData(1);//删除数据
mDBDao.updateData(1, new Tree("RedTree", 20, 5200f));//更新数据
mDBDao.deleteAllData();//删除所有数据

List<Tree> list = mDBDao.queryData(1);//查询id为1的数据
Log.v("-->", list.get(0).toString());

List<Tree> lists = mDBDao.queryDataList();//查询所有数据
for (Tree tree : lists) {
   Log.v("-->", tree.toString());
}

存储结果

技术分享

以上是关于一个封装类教你学会SQLite数据库的主要内容,如果未能解决你的问题,请参考以下文章

一个视屏的时间教你学会Java面向对象进阶

一个视屏的时间教你学会Java面向对象进阶

一个视屏的时间教你学会Java面向对象进阶

如果我想从另一个片段中添加书签,为啥我的书签单词没有保存到 sqlite 数据库?

使用片段从数据库 SQLite 获取数据时出错

如何在片段中访问 SQLite 数据到 ListView