Android uses SQLite database

Table of contents

Foreword:

create database

increase data

delete data

change the data

Query data

full code


Foreword:

Android provides the SQLiteOpenHelper interface for using the SQLite database. The provided method can be used very conveniently and concisely for adding, deleting, modifying and checking operations, but many variables need to be set when calling. So I wrote a more concise and saved tool class that can directly pass in the class.

This tool class is very simple to use. I identify and store the int class and the long class, and all other types use the string type. If you don't want to revert to a class object, maybe use the Json parsing toolkit

FastJSON or Gson

the effect will be better

Creating a database is recommended to be used in the onCreate method

Here you need to use the class that stores the data.

DBItem.java

public class DBItem {
    public int id = -1;

    public String name;

    public String drive;


    @Override
    public boolean equals(Object obj) {
        return obj instanceof DBItem && ((DBItem) obj).id == id;
    }

    @Override
    public String toString()  {
        return "{id: "+id+", name: "+name+", drive: "+drive+" }";
    }
}

create database

DBOpenHelper dbOpenHelper = DBOpenHelper.createDBHelper(
                context,
                "数据库名",
                DBOpenHelper.DBTable.asDBTable(DBItem.class),
                1);

increase data

dbOpenHelper.add(new DBItem());

delete data

// 根据对象删除
dbOpenHelper.remove(new DBItem());

//根据ID 删除
dbOpenHelper.remove(id);

change the data

// 直接修改内容 这个会识别内部的 id 根据ID更新
dbOpenHelper.set(new DBItem());

// 手动更新内容
dbOpenHelper.set(int id,ContentValues values);

Query data

// 获取全部的数据
List<DBItem> dbItems = dbOpenHelper.getAll(DBItem.class);

//根据ID查询到存入的类

DBItem dbItems = dbOpenHelper.get(id,DBItem.class);

full code

DBOpenHelper.java
public class DBOpenHelper extends SQLiteOpenHelper {

    private SQLiteDatabase database;

    private static String NAME = "drive";

    private static String TAG = NAME+"DB";

    private static String TABLE = NAME;

    private static String DB_FILE = NAME+".db";

    private static DBTable tables;

    private Context context;

    private DBOpenHelper(Context context,
                        String name,
                        SQLiteDatabase.CursorFactory factory,
                        int version) {
        super(context, name, factory, version);
        database = getWritableDatabase();
        this.context = context;

    }

    //id integer primary key autoincrement,step integer,time varchar(20)
    @Override
    public void onCreate(SQLiteDatabase db) {
       String sql = "create table "+TABLE+"("+tables.asSql()+")";

        db.execSQL(sql);
    }

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

    }
    /**
     * 增加数据
     * */
    public <T> DBOpenHelper add(T values){
        if(database != null){
            ContentValues contentValues = new ContentValues();
            Class c = values.getClass();
            for(Field field: c.getFields()){
                try {
                    if(field.getType() == int.class || field.getType() == long.class){
                        if(field.getName().equalsIgnoreCase("id")){
                            continue;
                        }
                        if(field.getType() == int.class ){
                            contentValues.put(field.getName(),field.getInt(values));
                        }else{
                            contentValues.put(field.getName(),field.getLong(values));
                        }
                    }else{
                        contentValues.put(field.getName(),field.get(values).toString());
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            database.insert(TABLE,null,contentValues);
        }else{
            Log.e(TAG,"数据库不存在");
        }
        return this;
    }

    /**
     * 增加数据
     * */
    public DBOpenHelper add(ContentValues values){
        if(database != null){
            database.insert(TABLE,null,values);
        }else{
            Log.e(TAG,"数据库不存在");
        }
        return this;
    }

    /**
     * 删除数据
     * */
    public DBOpenHelper remove(int id){
        if(database != null) {
            database.delete(TABLE, "id=?", new String[]{id + ""});
        }else{
            Log.e(TAG,"数据库不存在");
        }

        return this;
    }

    /**
     * 删除数据
     * */
    public DBOpenHelper remove(Object id){
        try{
            if(id.getClass().getField("id") != null){
                return remove(id.getClass().getField("id").getInt(id));
            }
        }catch (Exception e){
           throw new NullPointerException("传入的类必须要有 id");
        }
        return this;

    }

    public <T> DBOpenHelper set(T values){
        ContentValues contentValues = new ContentValues();
        Class c = values.getClass();
        int id = -1;
        for(Field field: c.getFields()){
            try {
                if(field.getType() == int.class || field.getType() == long.class){
                    if(field.getName().equalsIgnoreCase("id")){
                        id = field.getInt(values);
                        continue;
                    }
                    if(field.getType() == int.class ){
                        contentValues.put(field.getName(),field.getInt(values));
                    }else{
                        contentValues.put(field.getName(),field.getLong(values));
                    }
                }else{
                    contentValues.put(field.getName(),field.get(values).toString());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if(id == -1){
            throw new NullPointerException("无 id 信息");
        }
        return  set(id,contentValues);
    }

    /**
     * 更新数据
     * */
    public DBOpenHelper set(int id,ContentValues values){
        if(database != null) {
            database.update(TABLE, values, "id=?", new String[]{id + ""});
        }else {
            Log.e(TAG,"数据库不存在");
        }

        return this;
    }

    public <T> T get(int id, Class<T> a){
        T t = null;
        try (Cursor cursor = database.query(TABLE, null, "id=?",
                new String[]{id + ""}, null, null, null)) {
            t = a.newInstance();
            Class tc = t.getClass();
            t = explainClass(cursor,tc,t);
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
        return t;

    }

    public <T> LinkedList<T> getAll(Class<T> a){
        LinkedList<T> datas = new LinkedList<>();
        Cursor cursor = database.query(TABLE, null, null,
                null, null, null,null);
        while (cursor.moveToNext()){
            T t;
            try {
                t = a.newInstance();
                Class tc = t.getClass();
                t = explainClass(cursor,tc,t);
                datas.add(t);
            } catch (IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }

        }
        cursor.close();
        return datas;
    }

    public static class DBTable {
        LinkedHashMap<String,String> tables = new LinkedHashMap<>();

        public DBTable(String key,String value){
            tables.put(key, value);
        }

        public DBTable(Map<String,String> m){
            System.out.println(m);
            tables.putAll(m);
        }

        public DBTable put(String key,String value){
            tables.put(key, value);
            return this;
        }

        public String asSql(){
            StringBuilder s = new StringBuilder();
            for (Map.Entry<String,String> e:tables.entrySet()) {
                s.append(e.getKey()).append(" ").append(e.getValue()).append(",");
            }
            return s.toString().substring(0,s.length() - 1);

        }

        public static DBTable asDBTable(Class t){
            Field[] fields = t.getFields();
            LinkedHashMap<String,String> stringStringLinkedHashMap = new LinkedHashMap<>();
            boolean isId = false;
            // 先找自增id
            for(Field field: fields){
                if(field.getName().equalsIgnoreCase("id") && field.getType() == int.class){
                    //找到了
                    isId = true;
                }
            }
            if(!isId){
                throw new NullPointerException("数据库类需要一个id");
            }
            stringStringLinkedHashMap.put("id","integer primary key autoincrement");
            for(Field field: fields){
                if(field.getName().equalsIgnoreCase("id") && field.getType() == int.class){
                    //找到了
                    continue;
                }
                if(field.getType() == float.class || field.getType() == double.class){
                    stringStringLinkedHashMap.put(field.getName().toLowerCase(),field.getType().getName());
                }else{
                    stringStringLinkedHashMap.put(field.getName().toLowerCase(),"varchar(20)");
                }
            }
            return new DBTable(stringStringLinkedHashMap);

        }

    }

    public static DBOpenHelper createDBHelper(Context context,String tableName,DBTable tables,int version){
        DBOpenHelper.NAME = tableName;
        DBOpenHelper.tables = tables;
        return new DBOpenHelper(context,DBOpenHelper.DB_FILE,null,version);

    }

    private <T> T explainClass(Cursor cursor, Class tc, T t){
        for (String name : cursor.getColumnNames()) {
            try {
                Field field = tc.getField(name);
                if(field.getType() == int.class){
                    field.set(t, cursor.getInt(cursor.getColumnIndex(name)));
                }else
                if(field.getType() == float.class || field.getType() == double.class){
                    field.set(t, cursor.getFloat(cursor.getColumnIndex(name)));
                }else
                if(field.getType() == boolean.class){
                    field.set(t, Boolean.valueOf(cursor.getString(cursor.getColumnIndex(name))));

                }else
                if(field.getType() == long.class){
                    field.set(t, cursor.getLong(cursor.getColumnIndex(name)));

                }else{
                    field.set(t, cursor.getString(cursor.getColumnIndex(name)));
                }
            } catch (IllegalAccessException | NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return t;
    }

    public void clear(){
        context.deleteDatabase(DB_FILE);

    }

}

Afterword

It is very irrational to use getAll when there are too many data stores . It is best to rewrite it and change the reading to page reading.

Guess you like

Origin blog.csdn.net/qq_38174131/article/details/126122627