sqlite和GreenDao(一)

安卓编程,存储数据,特别是结果比较规则的数据,使用数据库来存储是比较合适的,常用的数据库有原生的sqlite和第三方GreenDao。
下面以一个存储录音的信息为例,展示两种数据库的用法。

sqlite

  • 录音信息Bean:RecorderInfo
public class RecorderInfo{
    private Long id;
    private String name;
    private String dater;
    private String type;
    private String length;
    private String size;
    private String r1;

    public RecorderInfo() {
    }

    public Long getId() {
        return this.id;
    }

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

    public String getName() {
        return this.name;
    }

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

    public String getDater() {
        return this.dater;
    }

    public void setDater(String dater) {
        this.dater = dater;
    }

    public String getType() {
        return this.type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getLength() {
        return this.length;
    }

    public void setLength(String length) {
        this.length = length;
    }

    public String getSize() {
        return this.size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getR1() {
        return this.r1;
    }

    public void setR1(String r1) {
        this.r1 = r1;
    }
  • 创建数据库的版本、表、字段:DBConstant
public class DBConstant {
    public static final String DATABASE_NAME = "db";
    public static final int DB_VERSION = 1;
    public static final String TABLE_NAME = "recorder_info";
    public static final String COLUMN_ID = "recorder_id";
    public static final String COLUMN_RECORDER_DATE = "recorder_date";
    public static final String COLUMN_RECORDER_TYPE = "recorder_type";
    public static final String COLUMN_RECORDER_TITLE = "recorder_title";
    public static final String COLUMN_RECORDER_DURATION = "recorder_duration";
    public static final String COLUMN_RECORDER_SIZE = "recorder_size";
    public static final String COLUMN_R1 = "r1";
}

  • 创建数据库的管理工具类:DBHelper
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.xxxx.soundrecorder.base.DBConstant;

public class DBHelper extends SQLiteOpenHelper {
    private static final String TAG=DBHelper.class.getSimpleName();
    public DBHelper(Context context) {
        super(context, DBConstant.DATABASE_NAME, null, DBConstant.DB_VERSION);
    }

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        createCityInfoTab(db);
        //模拟插入数据
        insertDefault(db)
    }

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

    }

    /**
     * 创建录音信息表
     *
     * @param db
     */
    private void createCityInfoTab(SQLiteDatabase db) {
        Log.d(TAG,"创建录音信息表");
        String strSQL = "create table "
                + DBConstant.TABLE_NAME
                + "(" + DBConstant.COLUMN_ID + " integer primary key autoincrement,"
                + DBConstant.COLUMN_RECORDER_DATA + " varchar(150), "
                + DBConstant.COLUMN_RECORDER_TITLE + " varchar(10), "
                + DBConstant.COLUMN_RECORDER_TYPE + " varchar(100), "
                + DBConstant.COLUMN_RECORDER_SIZE + " varchar(100), "
                + DBConstant.COLUMN_RECORDER_DURATION+ " varchar(100), "
                + DBConstant.COLUMN_R1 + " varchar(50))";
        db.execSQL(strSQL);
    }

    private void insertDefault(SQLiteDatabase db){
        ContentValues values = new ContentValues();
        values.put(DBConstant.COLUMN_RECORDER_DATE, "2018/5/5");
        values.put(DBConstant.COLUMN_RECORDER_TITLE, "recorder12515");
        values.put(DBConstant.COLUMN_RECORDER_TYPE, "3gp");
        values.put(DBConstant.COLUMN_RECORDER_DURATION, "12");
        db.insert(DBConstant.TABLE_NAME, null, values);
    }
}

  • 数据的操作工具:DBUtil
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.xxxx.soundrecorder.base.DBConstant;
import com.xxxx.soundrecorder.bean.RecorderInfo;

import java.util.ArrayList;
import java.util.List;

public class DBUtil {
    private final String TAG = DBUtil.class.getSimpleName();
    private DBHelper dbHelper = null;
    private static DBUtil instance = null;

    public static synchronized DBUtil getInstance(Context context) {
        if (instance == null) {
            instance = new DBUtil(context);
        }
        return instance;
    }

    private DBUtil(Context context) {
        dbHelper = new DBHelper(context);
    }

    /**
     * 查询所有录音
     *
     * @return 所有数据
     */
    public List<RecorderInfo> queryAllRecords() {
        List<RecorderInfo> cityInfoModels = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = dbHelper.getReadableDatabase();
            cursor = db.query(DBConstant.TABLE_NAME, new String[]{"*"}, null, null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    long id = cursor.getInt(cursor.getColumnIndex(DBConstant.COLUMN_ID));
                    String fileData = cursor.getString(cursor.getColumnIndex(DBConstant.COLUMN_RECORDER_DATE));
                    String fileDate = cursor.getString(cursor.getColumnIndex(DBConstant.COLUMN_RECORDER_TITLE));
                    String fileType = cursor.getString(cursor.getColumnIndex(DBConstant.COLUMN_RECORDER_TYPE));
                    String fileSize = cursor.getString(cursor.getColumnIndex(DBConstant.COLUMN_RECORDER_SIZE));
                    String fileLength = cursor.getString(cursor.getColumnIndex(DBConstant.COLUMN_RECORDER_DURATION));
                    String r1 = cursor.getString(cursor.getColumnIndex(DBConstant.COLUMN_R1));

                    RecorderInfo recorderInfo = new RecorderInfo();
                    recorderInfo.setId(id);
                    recorderInfo.setName(fileData);
                    recorderInfo.setDater(fileDate);
                    recorderInfo.setSize(fileSize);
                    recorderInfo.setType(fileType);
                    recorderInfo.setLength(fileLength);
                    recorderInfo.setR1(r1);

                    cityInfoModels.add(recorderInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }

            if (db != null) {
                db.close();
            }
        }

        return cityInfoModels;
    }

    /**
     * 插入录音
     *
     * @param recorderInfo 录音
     * @return 操作成功与否
     */
    public synchronized boolean insertRecord(RecorderInfo recorderInfo) {
        boolean isSuccess = false;
        if (recorderInfo == null) {
            return isSuccess;
        }

        SQLiteDatabase db = null;
        try {
            db = dbHelper.getWritableDatabase();
            //开启事务
            db.beginTransaction();
            ContentValues values = new ContentValues();
            values.put(DBConstant.COLUMN_RECORDER_DATE, recorderInfo.getName());
            values.put(DBConstant.COLUMN_RECORDER_TITLE, recorderInfo.getDater());
            values.put(DBConstant.COLUMN_RECORDER_TYPE, recorderInfo.getType());
            values.put(DBConstant.COLUMN_RECORDER_SIZE, recorderInfo.getSize());
            values.put(DBConstant.COLUMN_RECORDER_DURATION, recorderInfo.getLength());
            long no = db.insert(DBConstant.TABLE_NAME, null, values);
            if (no > 0) {
                isSuccess = true;
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }

        return isSuccess;
    }

    /**
     * 根据录音ID,删除文件
     *
     * @param id 录音ID
     * @return 操作成功与否
     */
    public synchronized boolean deleteRecord(int id) {
        boolean isSuccess = false;
        SQLiteDatabase db = null;
        try {
            db = dbHelper.getWritableDatabase();
            db.beginTransaction();
            int no = db.delete(DBConstant.TABLE_NAME, " " + DBConstant.COLUMN_ID + "=? ", new String[]{id + ""});
            if (no > 0) {
                isSuccess = true;
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }

        return isSuccess;
    }

    /**
     * 根据录音名称,删除文件
     *
     * @param fileName 录音名称
     * @return 操作成功与否
     */
    public synchronized boolean deleteRecordByName(String fileName) {
        Log.i(TAG, "deleteRecorderByName=" + fileName);
        boolean isSuccess = false;
        SQLiteDatabase db = null;
        try {
            db = dbHelper.getWritableDatabase();
            db.beginTransaction();
            int no = db.delete(DBConstant.TABLE_NAME, " " + DBConstant.COLUMN_RECORDER_DATE + "=? ", new String[]{fileName + ""});

            if (no > 0) {
                isSuccess = true;
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }

        return isSuccess;
    }

    /**
     * 根据录音ID,更新录音名称
     *
     * @param id          录音ID
     * @param newFileName 录音名称
     * @returnid 操作成功与否
     */
    public synchronized boolean updateRecordById(long id, String newFileName) {
        Log.i(TAG, "deleteRecorderByName=" + id + ",newFileName=" + newFileName);
        boolean isSuccess = false;
        SQLiteDatabase db = null;
        try {
            db = dbHelper.getWritableDatabase();
            db.beginTransaction();
            ContentValues values = new ContentValues();
            values.put(DBConstant.COLUMN_RECORDER_DATE, newFileName);
//            db.update("tablename", values, "name=?", new String[]{"xiadong"});
//db.update("tablename",values,"name=? AND age=?",new Object{"xiadong", 20});

            db.update(DBConstant.TABLE_NAME, values, DBConstant.COLUMN_ID + "=?", new String[]{id + ""});
            isSuccess = true;
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }

        return isSuccess;
    }
}

好了。上面就是sqlite的基本用法。greendao的有时间整理在写….

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