公共代码参考(SQLiteOpenHelper)

package com.fredric.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/*-
 * sqlite数据库操作封装
 */

public class DBHelper extends SQLiteOpenHelper{
    private final static String DB_NAME  = "demo.db";
    private final static String TBL_NAME = "users";
    private static final int DB_VERSION  = 1;
    private final static String CREATE_TBL 
        = "CREATE TABLE IF NOT EXISTS users (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, password VARCHAR)"; 
    private SQLiteDatabase db;

    public DBHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }
    
    public DBHelper(Context context){  
        this(context, DB_NAME, null, DB_VERSION);  
    }

    //当数据库第一次被建立的时候被执行,例如创建表,初始化数据等
    @Override
    public void onCreate(SQLiteDatabase db) {
        this.db = db;
        db.execSQL(CREATE_TBL);
    }

    //当数据库需要被更新的时候执行,例如删除表,创建表
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        
    }
    
    public void insert(ContentValues values){  
        SQLiteDatabase db = getWritableDatabase();  
        db.insert(TBL_NAME, null, values);  
        db.close();  
    }  
          
    //查询方法  
    public Cursor rawQuery(String sql, String[] args){  
        SQLiteDatabase db = getReadableDatabase();  
        Cursor cursor = db.rawQuery(sql, args);  
        return cursor;           
    }  
          
    //删除数据  
    public void delete(int id){  
        SQLiteDatabase db = getWritableDatabase();  
        db.delete(TBL_NAME, "_id=?", new String[]{String.valueOf(id)});  
    }  
                
    //更新数据库的内容  
    public void update(ContentValues values, String whereClause, String[] whereArgs){  
        SQLiteDatabase db = getWritableDatabase();  
        db.update(TBL_NAME, values, whereClause, whereArgs);  
    }  
          
    //关闭数据库  
    public void close(){  
        if(db != null){  
            db.close();  
        }  
    }     
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。