DBImpl基于ormlite数据库的操作,数据读写效率更高


import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @param
 * @Comments : 功能
 * @Author : Lampo
 * @CreateDate : 2019/12/26 11:18
 * @ModifiedBy : Lampo
 * @ModifiedDate : 2019/12/26 11:18
 * @Modified :
 */

public class DBImpl {
    private SQLiteDatabase db;
    public ImplDataBase mBaseDao;
    private static DBImpl dbimpl;

    public DBImpl() {
        DatabaseHelper mHelper = DatabaseHelper.getInstance(CitApplication.getInstance());
        mBaseDao = new ImplDataBase(mHelper);
        db = mHelper.getWritableDatabase();
    }

    public static DBImpl getInstance() {
        if (dbimpl == null)
            dbimpl = new DBImpl();
        return dbimpl;
    }

    public <T> long insertVo(T t) {
        long index;
        try {
            db.beginTransaction();
            String tableName = t.getClass().getAnnotation(DatabaseTable.class).tableName();
            ContentValues values = new ContentValues();
            Field[] fields = t.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    if (!field.getAnnotation(DatabaseField.class).generatedId()) {
                        values.put(field.getName(), String.valueOf(field.get(t)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            index = db.insert(tableName, "", values);
            if (index == -1) {
                index = mBaseDao.create(t);
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            ExceptionLogUtil.getInstance().save(e);
            index = -1;
        }
        FileUtils.copyDB();
        return index;
    }

    public int delete(Class cla) {
        int index;
        try {
            db.beginTransaction();
            String tableName = cla.getClass().getAnnotation(DatabaseTable.class).tableName();
            index = db.delete(tableName, "", new String[]{});
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            index = -1;
        }
        FileUtils.copyDB();
        return index;
    }

    public <T> void deleteListVo(List<T> list) {
        for (T t : list) {
            deleteVo(t);
        }
    }

    public <T> int deleteVo(T t) {
        int index;
        try {
            db.beginTransaction();
            String tableName = t.getClass().getAnnotation(DatabaseTable.class).tableName();
            String value = "";
            StringBuffer keyBuffer = new StringBuffer();
            Field[] fields = t.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    if (field.getAnnotation(DatabaseField.class).generatedId()) {
                        keyBuffer.append(field.getName()).append(" = ? ");
                        value = String.valueOf(field.get(t));
                        continue;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            index = db.delete(tableName, keyBuffer.toString(), new String[]{value});
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            ExceptionLogUtil.getInstance().save(e);
            index = -1;
        }
        FileUtils.copyDB();
        return index;
    }

    public <T> int updateVo(T t) {
        int index;
        try {
            db.beginTransaction();
            String tableName = t.getClass().getAnnotation(DatabaseTable.class).tableName();
            ContentValues values = new ContentValues();
            String value = "";
            StringBuffer keyBuffer = new StringBuffer();
            Field[] fields = t.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    if (field.getAnnotation(DatabaseField.class).generatedId()) {
                        keyBuffer.append(field.getName()).append(" = ? ");
                        value = String.valueOf(field.get(t));
                    } else {
                        values.put(field.getName(), String.valueOf(field.get(t)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            index = db.update(tableName, values, keyBuffer.toString(), new String[]{value});
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            ExceptionLogUtil.getInstance().save(e);
            index = -1;
        }
        FileUtils.copyDB();
        return index;
    }

    public <T> List<T> queryVo() {
        List<T> list = new ArrayList<>();
        return list;
    }

    public <T> T queryFrist(Class<T> tClass) {
        List<T> list = queryAll(tClass);
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    public <T> T queryLast(Class<T> tClass) {
        List<T> list = queryAll(tClass);
        if (list != null && !list.isEmpty()) {
            return list.get(list.size() - 1);
        }
        return null;
    }

    public <T> List<T> queryForDetail(Map<String, Object> mDbWhere, Class<T> tClass) {
        List<T> list = new ArrayList<>();
        try {
            PDALogger.e("queryForDetail ==start=");
            db.beginTransaction();
            T t = tClass.newInstance();
            String tableName = t.getClass().getAnnotation(DatabaseTable.class).tableName();
            StringBuffer selection = new StringBuffer();
            int size = mDbWhere.size();
            int count = 0;
            String[] selectionArgs = new String[]{};
            for (String key : Collections.list(Collections.enumeration(mDbWhere.keySet()))) {
                selection.append(key).append("=?");
                if (count != size) {
                    selection.append(" AND ");
                }
                selectionArgs[count] = String.valueOf(mDbWhere.get(key));
                count++;
            }
            Cursor cursor = db.query(tableName, null, selection.toString(), selectionArgs, null, null, null);
            if (cursor.getColumnCount() <= 0) {
                return list;
            } else {
                while (cursor.moveToNext()) {
                    T t1 = readCursor(tClass, cursor);
                    list.add(t1);
                }
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
        PDALogger.e("queryForDetail ==end=");
        return list;
    }

    public <T> List<T> queryAll(Class<T> tClass) {
        List<T> list = new ArrayList<>();
        PDALogger.e("queryForDetail =queryAll=start=");
        try {
            db.beginTransaction();
            T t = tClass.newInstance();
            String tableName = t.getClass().getAnnotation(DatabaseTable.class).tableName();
            String sql = "SELECT * FROM " + tableName;
            Cursor cursor = db.rawQuery(sql, null);
            if (cursor.getColumnCount() <= 0) {
                return list;
            } else {
                while (cursor.moveToNext()) {
                    T t1 = readCursor(tClass, cursor);
                    list.add(t1);
                }
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
        PDALogger.e("queryForDetail =queryAll=end=");
        return list;
    }

    public <T> T readCursor(Class<T> tClass, Cursor cursor) throws Exception {
        T t = tClass.newInstance();
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object a = getColumeValue(field, cursor);
                field.set(t, a);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return t;
    }

    private Object getColumeValue(Field field, Cursor cursor) throws IllegalAccessException {
        Object object = new Object();
        String type = field.getType().getSimpleName();
        switch (type) {
            case "int":
            case "Integer":
                object = cursor.getInt(cursor.getColumnIndex(field.getName()));
                break;
            case "String":
            case "java.lang.String":
                object = cursor.getString(cursor.getColumnIndex(field.getName()));
                break;
            case "boolean":
            case "java.lang.Boolean":
                object = cursor.getInt(cursor.getColumnIndex(field.getName())) == 1;
                break;
            case "double":
            case "java.lang.Double":
                object = cursor.getDouble(cursor.getColumnIndex(field.getName()));
                break;
            case "float":
            case "java.lang.Float":
                object = cursor.getFloat(cursor.getColumnIndex(field.getName()));
                break;
            case "long":
            case "java.lang.Long":
                object = cursor.getLong(cursor.getColumnIndex(field.getName()));
                break;
            case "short":
            case "java.lang.Short":
                object = cursor.getShort(cursor.getColumnIndex(field.getName()));
                break;
        }
        return object;

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值