android基础巩固之db存储

db文件导出

C:\>adb pull "data/data/com.example.advance/databases/book.db"
data/data/com.example.advance/database...lled. 2.8 MB/s (20480 bytes in 0.007s)

C:\>

db创建

public class BookDbHelper extends SQLiteOpenHelper {
    public BookDbHelper(Context context) {
        super(context, BasicDBAppConst.BOOKDB_NAME, null, BasicDBAppConst.BOOKDB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS t_person (personid integer primary key " +
                "autoincrement, name varchar(20), age INTEGER)");
    }

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

dao语句对比 (原生api和sql语句使用对比 )

原生api

public class PersonDao implements IPersonDao {
    private static PersonDao MDAO = null;
    private BookDbHelper mBookDbHelper;

    private PersonDao() {

    }

    private PersonDao(Context context) {
        mBookDbHelper = new BookDbHelper(context);
    }

    public static PersonDao getDao(Context context) {
        if (MDAO == null) {
            synchronized (PersonDao.class) {
                if (MDAO == null) {
                    MDAO = new PersonDao(context);
                }
            }
        }
        return MDAO;
    }

    @Override
    public boolean insert(PersonInfo info) {
        SQLiteDatabase database = mBookDbHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(PersonInfo.COLOUMN_PERSON_NAME, info.getName());
        contentValues.put(PersonInfo.COLOUMN_PERSON_AGE, info.getAge());
        long r = database.insert(PersonInfo.TABNAME, null, contentValues);
        LoggerUtils.loge(" insert r = " + r);
        return r == -1;
    }

    @Override
    public List<PersonInfo> query() {
        SQLiteDatabase database = mBookDbHelper.getReadableDatabase();
        List<PersonInfo> list = new ArrayList<>();
        Cursor cursor = database.query(PersonInfo.TABNAME, null, null, null, null, null, null);
        PersonInfo personInfo = null;
        while (cursor.moveToNext()) {
            personInfo = new PersonInfo();
            personInfo.setId(cursor.getInt(cursor.getColumnIndex(PersonInfo.COLOUMN_PERSON_ID)));
            personInfo.setName(cursor.getString(cursor.getColumnIndex(PersonInfo
                    .COLOUMN_PERSON_NAME)));
            personInfo.setAge(cursor.getInt(cursor.getColumnIndex(PersonInfo.COLOUMN_PERSON_AGE)));
            list.add(personInfo);
        }
        return list;
    }
}

sql语句

public class PersonDao implements IPersonDao {
    private static PersonDao MDAO = null;
    private BookDbHelper mBookDbHelper;

    private PersonDao() {

    }

    private PersonDao(Context context) {
        mBookDbHelper = new BookDbHelper(context);
    }

    public static PersonDao getDao(Context context) {
        if (MDAO == null) {
            synchronized (PersonDao.class) {
                if (MDAO == null) {
                    MDAO = new PersonDao(context);
                }
            }
        }
        return MDAO;
    }

    @Override
    public boolean insert(PersonInfo info) {
        SQLiteDatabase database = mBookDbHelper.getWritableDatabase();
        int r = 0;
        try {
            database.execSQL("insert into " + PersonInfo.TABNAME + " ( " + PersonInfo
                    .COLOUMN_PERSON_NAME + " , " +
                    PersonInfo.COLOUMN_PERSON_AGE + ") values ( ?,? ) ", new String[]{info
                    .getName(), info.getAge() + ""});
        } catch (SQLException e) {
            e.printStackTrace();
            r = -1;
        }
        return r == -1;
    }
    
    @Override
    public List<PersonInfo> query() {
        SQLiteDatabase database = mBookDbHelper.getReadableDatabase();
        List<PersonInfo> list = new ArrayList<>();

        String sql = "select * from " + PersonInfo.TABNAME;
        Cursor cursor = database.rawQuery(sql, null);
        PersonInfo personInfo = null;
        while (cursor.moveToNext()) {
            personInfo = new PersonInfo();
            personInfo.setId(cursor.getInt(cursor.getColumnIndex(PersonInfo.COLOUMN_PERSON_ID)));
            personInfo.setName(cursor.getString(cursor.getColumnIndex(PersonInfo
                    .COLOUMN_PERSON_NAME)));
            personInfo.setAge(cursor.getInt(cursor.getColumnIndex(PersonInfo.COLOUMN_PERSON_AGE)));
            list.add(personInfo);
        }
        return list;
    }
}

增强型的封装操作

com.example.dblib.BaseDAO

public abstract class BaseDAO<T> implements IBaseDao<T> {

    protected BaseSqliteDbHelper mSqliteDbHelper;
    /**
     * 用于组拼sql语句
     */
    protected StringBuilder sqlBuilder = new StringBuilder();

    protected SQLiteDatabase getWriteDb() {
        return mSqliteDbHelper.getWritableDatabase();
    }

    protected SQLiteDatabase getReadDb() {
        return mSqliteDbHelper.getReadableDatabase();
    }

    @NonNull
    protected String printLog() {
        String sql = sqlBuilder.toString();
        Log.e("dbsql", sql);
        return sql;
    }

}

dao实现类

public class MusicDBDAO extends BaseDAO<MusicTabinfo> {
    private static MusicDBDAO INSTANCE = null;

    private MusicDBDAO() {
        mSqliteDbHelper = new MusicDBHelper(BaseApp.getAppInstance());
    }

    public static MusicDBDAO getInstance() {
        if (INSTANCE == null) {
            synchronized (MusicDBDAO.class) {
                if (INSTANCE == null) {
                    INSTANCE = new MusicDBDAO();
                }
            }
        }
        return INSTANCE;
    }

    @Override
    public int add(MusicTabinfo musicTabinfo) {
        if (musicTabinfo == null)
            return -1;

        sqlBuilder.setLength(0);
        sqlBuilder.append("insert into ").append(MusicTabinfo.TABLE_NAME).append(" ( ");
        sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_MUSIC_NAME).append(" , ");
        sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_AUTHOR).append(" , ");
        sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_PUBLISH_NAME).append(" , ");
        sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_DESC).append(" ) values ( ");
        sqlBuilder.append("?,?,?,? ) ");

        printLog();
        try {
            getWriteDb().execSQL(sqlBuilder.toString(), new String[]{
                    musicTabinfo.getMusicName(), musicTabinfo.getAuthor(), musicTabinfo
                    .getPublishTime(), musicTabinfo.getDesc()});
            return 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }


    @Override
    public int addAll(List<MusicTabinfo> list) {
        int errorNum = 0;
        for (MusicTabinfo tabinfo : list) {
            try {
                add(tabinfo);
            } catch (Exception e) {
                e.printStackTrace();
                errorNum++;
            }
        }
        // 有出错则返回-1
        return (errorNum == 0 ? 0 : -1);
    }

    @Override
    public int delete(MusicTabinfo musicTabinfo) {
        sqlBuilder.setLength(0);

        sqlBuilder.append("delete from ").append(MusicTabinfo.TABLE_NAME);
        sqlBuilder.append(" where ").append(MusicTabinfo.COLOUMN_NAME_MUSIC_NAME).append(" = ? ");
        sqlBuilder.append(" & ").append(MusicTabinfo.COLOUMN_NAME_ID).append(" = ? ");
        printLog();

        try {
            getWriteDb().execSQL(sqlBuilder.toString(), new String[]{musicTabinfo.getMusicName(),
                    musicTabinfo.getMusicId() + ""});
            return 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int deleteById(int id) {
        sqlBuilder.setLength(0);

        sqlBuilder.append("delete from ").append(MusicTabinfo.TABLE_NAME);
        sqlBuilder.append(" where ").append(MusicTabinfo.COLOUMN_NAME_ID).append(" = ? ");
        printLog();

        try {
            getWriteDb().execSQL(sqlBuilder.toString(), new String[]{id + ""});
            return 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }


    @Override
    public int update(MusicTabinfo musicTabinfo) {
        if (musicTabinfo == null)
            return -1;
        sqlBuilder.setLength(0);


        // 先查询再更新避免没有设置的数据被清除掉了
        sqlBuilder.append("update ").append(MusicTabinfo.TABLE_NAME);
        sqlBuilder.append(" set ");
        sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_AUTHOR).append(" = ? , ");
        sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_PUBLISH_NAME).append(" = ? ,");
        sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_DESC).append(" = ? ");
        sqlBuilder.append(" where ").append(MusicTabinfo.COLOUMN_NAME_MUSIC_NAME).append(" = ? ");

        try {
            printLog();
            getWriteDb().execSQL(sqlBuilder.toString(), new String[]{musicTabinfo.getAuthor(),
                    musicTabinfo.getPublishTime(), musicTabinfo.getDesc(), musicTabinfo
                    .getMusicName()});
            return 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int updateById(int id, Map<String, Object> params) {
        if (id == -1 || id == 0 || params == null || params.size() == 0)
            return -1;

        // 先查询在数据库中是否存在
        MusicTabinfo dbInfo = queryById(id);

        Set<String> keySet = params.keySet();
        if (dbInfo != null) {
            // 存在就更新
            fillTabData(params, dbInfo, keySet);

            sqlBuilder.setLength(0);
            sqlBuilder.append("update ").append(MusicTabinfo.TABLE_NAME);
            sqlBuilder.append(" set ");
            sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_AUTHOR).append(" = ? , ");
            sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_PUBLISH_NAME).append(" = ? , ");
            sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_DESC).append(" = ? , ");
            sqlBuilder.append(MusicTabinfo.COLOUMN_NAME_MUSIC_NAME).append(" = ? ");
            sqlBuilder.append(" where ").append(MusicTabinfo.COLOUMN_NAME_ID).append(" = ?");
            printLog();
            try {
                getWriteDb().execSQL(sqlBuilder.toString(), new String[]{dbInfo.getAuthor(),
                        dbInfo.getPublishTime(), dbInfo.getDesc(), dbInfo.getMusicName(),
                        id + ""});
                return 0;
            } catch (SQLException e) {
                e.printStackTrace();
                return -1;
            }
        } else {
            // 不存在就创建,并插入数据库
            dbInfo = new MusicTabinfo();
            fillTabData(params, dbInfo, keySet);
            return add(dbInfo);
        }
    }

    private void fillTabData(Map<String, Object> params, MusicTabinfo dbInfo, Set<String> keySet) {
        // 数据库中不存在就添加到数据库中
        if (keySet.contains(MusicTabinfo.COLOUMN_NAME_AUTHOR)) {
            dbInfo.setAuthor((String) params.get(MusicTabinfo.COLOUMN_NAME_AUTHOR));
        }

        if (keySet.contains(MusicTabinfo.COLOUMN_NAME_PUBLISH_NAME)) {
            dbInfo.setPublishTime((String) params.get(MusicTabinfo.COLOUMN_NAME_PUBLISH_NAME));
        }

        if (keySet.contains(MusicTabinfo.COLOUMN_NAME_DESC)) {
            dbInfo.setDesc((String) params.get(MusicTabinfo.COLOUMN_NAME_DESC));
        }

        if (keySet.contains(MusicTabinfo.COLOUMN_NAME_MUSIC_NAME)) {
            dbInfo.setMusicName((String) params.get(MusicTabinfo.COLOUMN_NAME_MUSIC_NAME));
        }
    }


    @Override
    public MusicTabinfo queryById(int id) {
        MusicTabinfo tabinfo = new MusicTabinfo();
        sqlBuilder.setLength(0);

        sqlBuilder.append("select * from ").append(MusicTabinfo.TABLE_NAME);
        sqlBuilder.append(" where ").append(MusicTabinfo.COLOUMN_NAME_ID).append(" = ?");

        Cursor cursor = null;
        try {
            cursor = getReadDb().rawQuery(sqlBuilder.toString(), new String[]{id + ""});
            cursor.moveToFirst();
            int _id = cursor.getInt(cursor.getColumnIndex(MusicTabinfo.COLOUMN_NAME_ID));
            String _name = cursor.getString(cursor.getColumnIndex(MusicTabinfo
                    .COLOUMN_NAME_MUSIC_NAME));
            String _author = cursor.getString(cursor.getColumnIndex(MusicTabinfo
                    .COLOUMN_NAME_AUTHOR));
            String _publish_time = cursor.getString(cursor.getColumnIndex(MusicTabinfo
                    .COLOUMN_NAME_PUBLISH_NAME));
            String _desc = cursor.getString(cursor.getColumnIndex(MusicTabinfo.COLOUMN_NAME_DESC));
            tabinfo = new MusicTabinfo(_id, _name, _publish_time, _author, _desc);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }

        return tabinfo;
    }

    @Override
    public List<MusicTabinfo> queryAll() {
        Cursor cursor = getReadDb().rawQuery("select * from " + MusicTabinfo.TABLE_NAME, null);
        List<MusicTabinfo> list = new ArrayList<>();
        MusicTabinfo tabinfo = null;
        while (cursor.moveToNext()) {
            int _id = cursor.getInt(cursor.getColumnIndex(MusicTabinfo.COLOUMN_NAME_ID));
            String _name = cursor.getString(cursor.getColumnIndex(MusicTabinfo
                    .COLOUMN_NAME_MUSIC_NAME));
            String _author = cursor.getString(cursor.getColumnIndex(MusicTabinfo
                    .COLOUMN_NAME_AUTHOR));
            String _publish_time = cursor.getString(cursor.getColumnIndex(MusicTabinfo
                    .COLOUMN_NAME_PUBLISH_NAME));
            String _desc = cursor.getString(cursor.getColumnIndex(MusicTabinfo.COLOUMN_NAME_DESC));
            tabinfo = new MusicTabinfo(_id, _name, _publish_time, _author, _desc);
            list.add(tabinfo);
        }
        cursor.close();
        return list;
    }
}

测试类的编写

环境配置

android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

测试代码

@RunWith(AndroidJUnit4.class)
public class PersonDaoTest {

    private final String T_CNAME = this.getClass().getSimpleName();
    private PersonDao mBookDao;
    private Context mContext;
    private SharedPreferences mSp;

    @Before
    public void setUp() throws Exception {
        LoggerUtils.loge(T_CNAME + " setUp ");
        // 上下文别用错了,否则会崩溃的
        mContext = BaseApp.getContext();
        mBookDao = PersonDao.getDao(mContext);

        mSp = mContext.getSharedPreferences("test_basic.config",
                Context.MODE_PRIVATE);
        LoggerUtils.loge(T_CNAME + " mBookDao =  " + mBookDao);
    }

    @Test
    public void insert() {
        mSp.edit().putString("aciton", "insert").commit();
        PersonInfo tabInfo = new PersonInfo();
        tabInfo.setName("陈龙");
        tabInfo.setAge(22);
        mBookDao.insert(tabInfo);
        tabInfo = new PersonInfo();
        tabInfo.setName("陈龙");
        tabInfo.setAge(22);
        mBookDao.insert(tabInfo);
        tabInfo = new PersonInfo();
        tabInfo.setName("陈龙");
        tabInfo.setAge(22);
        mBookDao.insert(tabInfo);
        tabInfo = new PersonInfo();
        tabInfo.setName("陈龙");
        tabInfo.setAge(22);
        mBookDao.insert(tabInfo);
        tabInfo = new PersonInfo();
        tabInfo.setName("陈龙");
        tabInfo.setAge(22);
        mBookDao.insert(tabInfo);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void query() {
        mSp.edit().putString("aciton", "query").commit();
        LoggerUtils.loge(T_CNAME + " query ");
        List<PersonInfo> infos = mBookDao.query();
        for (PersonInfo info : infos) {
            LoggerUtils.loge(T_CNAME + " info =  " + info.toString());
        }
    }
}

出错分析

log

01-22 12:39:59.658 5453-5468/? E/dbsql: update t_music set author = ? , publish_time = ? ,desc =  where music_name = ? 
01-22 12:39:59.658 5453-5468/? E/SQLiteLog: (1) near "where": syntax error
    原文作者:草蜢的逆袭
    原文地址: https://www.jianshu.com/p/373f7f683cf0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞