关于Sqlite的简单使用与总结,可直接模仿用到现有项目中~

最近刚刚开通了blog,目的就是把自己常用到的一些技术点和一些模版积累下来,方便后期做项目的时候可以直接拿出模版套着使用,而不用每次都需要找度娘去解决,非常的不方便~~~
今天的第一篇blog就把我关于sqlite常用的一些套路分享出来(其实大部分也是模仿其他大牛写的),方便我们大家共同学习进步,有什么不对的地方,希望看到的人儿批评指正,哈哈~~~


1.第一种模式:


  先看SQLiteOpenHelper类:
public class SQLHelper extends SQLiteOpenHelper {


    public static final String DB_NAME = "database.db";// 数据库名称
    public static final int VERSION = 1;
    public static final String TABLE_PERSON = "PersonItem";// 数据表
    public static final String ID = "id";//
    public static final String NAME = "name";
    public static final String SEX = "sex";
    public static final String AGE = "age";
    private Context context;


    public SQLHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
        this.context = context;
    }
    public Context getContext() {
        return context;
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO 创建数据库后,对数据库的操作
        String sql = "create table if not exists " + TABLE_CHANNEL +
                "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                ID + " INTEGER , " +
                NAME + " TEXT , " +
                AGE + " INTEGER , " +
                SEX + " TEXT)";
        db.execSQL(sql);
    }


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

     再看DBUtils类:
public class DBUtils {
    private static DBUtils mInstance;
    private SQLHelper mSQLHelp;
    private SQLiteDatabase mSQLiteDatabase;
    public DBUtils(Context context) {
        mSQLHelp = new SQLHelper(context);
        mSQLiteDatabase = mSQLHelp.getWritableDatabase();
    }


    public static DBUtils getInstance(Context context){
        if (mInstance == null){
            mInstance = new DBUtils(context);
        }
        return mInstance;
    }


    public void close() {
        mSQLHelp.close();
        mSQLHelp = null;
        mSQLiteDatabase.close();
        mSQLiteDatabase = null;
        mInstance = null;
    }
    /**
     * 插入数据
     */
    public void insertData(ContentValues values){
        mSQLiteDatabase.insert(SQLHelper.TABLE_PERSON, null, values);
    }
    /**
     * 修改数据
     */
    public void updateData(ContentValues values, String whereClause,
                           String[] whereArgs){
        mSQLiteDatabase.update(SQLHelper.TABLE_PERSON, values, whereClause,
                whereArgs);
    }
    /**
     * 删除数据
     */
    public void deleteData(String whereClause, String[] whereArgs){
        mSQLiteDatabase.delete(SQLHelper.TABLE_PERSON, whereClause, whereArgs);
    }
    /**
     * 按搜索条件查询数据
     */
    public Cursor selectData(String[] columns, String selection,
                             String[] selectionArgs, String groupBy, String having,
                             String orderBy){
        Cursor cursor = mSQLiteDatabase.query(SQLHelper.TABLE_PERSON, columns, selection,
                selectionArgs, groupBy, having, orderBy);
        return cursor;
    }
}
 2.第二种模式(纯粹是为了做对比,从别的地方挪过来的):


      先看SQLiteHelper类:
     
public class SqliteDataHelper extends SQLiteOpenHelper {
    public static final String TABLE_NOTES = "notes";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_LAST_REVIEWED = "last_reviewed";
    public static final String COLUMN_TOTAL_REVIEWS = "total_reviews";
    public static final String COLUMN_CONTENT = "content";


    private static final String DATABASE_NAME = "notes.db";
    private static final int DATABASE_VERSION = 1;
    public SqliteDataHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(" CREATE TABLE " + TABLE_NOTES + " (" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_TITLE + " TEXT NOT NULL, " +
                COLUMN_LAST_REVIEWED + " TEXT NOT NULL, " +
                COLUMN_TOTAL_REVIEWS + " TEXT NOT NULL, " +
                COLUMN_CONTENT + " TEXT NOT NULL);"
        );
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
        onCreate(db);
    }
}
     再看DBManager类:
     public class NotesDataManager {
    private SqliteDataHelper helper;
    private SQLiteDatabase database;


    public NotesDataManager(Context context) {
        helper = new SqliteDataHelper(context);
    }
    public void open() throws SQLException {
        database = helper.getWritableDatabase();
    }
    public void close() {
        helper.close();
    }
    public long insertNotes(String title, String content){
        this.open();
        ContentValues values = new ContentValues();
        values.put(SqliteDataHelper.COLUMN_TITLE,title);
        values.put(SqliteDataHelper.COLUMN_CONTENT,content);
        long currentTime = System.currentTimeMillis();
        values.put(SqliteDataHelper.COLUMN_LAST_REVIEWED,currentTime);
        values.put(SqliteDataHelper.COLUMN_TOTAL_REVIEWS,0);
        long insert = database.insert(SqliteDataHelper.TABLE_NOTES, null, values);
        this.close();
        return insert;
    }
    public long deleteNotes(String title, String content){
        this.open();
        int delete = database.delete(SqliteDataHelper.TABLE_NOTES, SqliteDataHelper.COLUMN_CONTENT + " = ? ", new String[]{String.valueOf(content)});
        return delete;
    }
    public long incrementTotalReviews(String content){
        this.open();
        String sql = "UPDATE " + SqliteDataHelper.TABLE_NOTES +
                " SET " + SqliteDataHelper.COLUMN_TOTAL_REVIEWS + "=" + SqliteDataHelper.COLUMN_TOTAL_REVIEWS + "+1"+
                "WHERE" + SqliteDataHelper.COLUMN_CONTENT + " >= '" + content +"'";
        database.execSQL(sql);   //这是sqlite的另外一种写法

        this.close();
        return 0;
    }
    public long modifyLastSeen(String content)
    {
        this.open();
        String sql = "UPDATE " + SqliteDataHelper.TABLE_NOTES +
                " SET " + SqliteDataHelper.COLUMN_LAST_REVIEWED + "=" + System.currentTimeMillis()+
                " WHERE " + SqliteDataHelper.COLUMN_CONTENT + " >= '" + content+"'";


        database.execSQL(sql);

        /*database.execSQL("UPDATE " + SQLiteHelper.TABLE_NOTES + " SET "
                + SQLiteHelper.COLUMN_TOTAL_REVIEWS + " = " + SQLiteHelper.COLUMN_TOTAL_REVIEWS + " +1 WHERE "
                + SQLiteHelper.COLUMN_CONTENT + " = " +content);*/
        this.close();
        return 0;
    }
    public ArrayList<NoteItem> getAllNotes(){
        this.open();
        ArrayList<NoteItem> noteItemList = new ArrayList<NoteItem>();
        Cursor cursor = database.rawQuery("select * from notes", null);
        if (cursor.moveToFirst()){
            while (!cursor.isAfterLast()){
                String title = cursor.getString(cursor.getColumnIndex(SqliteDataHelper.COLUMN_TITLE));
                String last_reviewed = cursor.getString(cursor.getColumnIndex(SqliteDataHelper.COLUMN_LAST_REVIEWED));
                String total_reviews = cursor.getString(cursor.getColumnIndex(SqliteDataHelper.COLUMN_TOTAL_REVIEWS));
                String content  = cursor.getString(cursor.getColumnIndex(SqliteDataHelper.COLUMN_CONTENT));


                NoteItem item = new NoteItem(title,last_reviewed,total_reviews,content);
                noteItemList.add(item);
                cursor.moveToNext();
            }
        }
        this.close();
        return noteItemList;
    }


    public List<NoteItem> getAllNotesForNotification() {
        this.open();
        List<NoteItem> items = new ArrayList<NoteItem>();
        Cursor  cursor = database.rawQuery("select * from notes",null);


        if (cursor .moveToFirst()) {
            while (!cursor.isAfterLast()) {
                String title = cursor.getString(cursor.getColumnIndex(SqliteDataHelper.COLUMN_TITLE));
                String last_reviewed = cursor.getString(cursor.getColumnIndex(SqliteDataHelper.COLUMN_LAST_REVIEWED));
                String total_reviews = cursor.getString(cursor.getColumnIndex(SqliteDataHelper.COLUMN_TOTAL_REVIEWS));
                String content  = cursor.getString(cursor.getColumnIndex(SqliteDataHelper.COLUMN_CONTENT));


                NoteItem item = new NoteItem(title,last_reviewed,total_reviews,content);
                long past_epoch = Long.valueOf(item.last_reviewed);
                long current_epoch = System.currentTimeMillis();
                long difference = current_epoch - past_epoch;
                if (notificationRequired(difference,Integer.valueOf(item.total_reviews))) {
                    items.add(item);
                }
                cursor.moveToNext();
            }
        }
        this.close();
        return items;
    }
}上述类只需要看标红的就可以,主要是学习有哪几种sql的写法。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值