Android 操作SQLite数据库增删改查

首次发布:2020-10-06 20:34
数据库帮助类
public class DatabaseHelper extends SQLiteOpenHelper {
    //转载请保留 http://www.luofenming.com/show.aspx?id=ART2020100600001

    /**
     * 如果有SQLite数据文件 则不创建新的SQLite数据库文件
     * @param context 上下文
     * @param fileName 数据库文件名
     */
    public DatabaseHelper(@Nullable Context context,String fileName) {
        super(context, fileName, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

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

    }
}
SQLite数据库增删除改查
//建表
public void createDatabase(){
    DatabaseHelper helper=new DatabaseHelper(this,"lqwvje.db");
    SQLiteDatabase db=  helper.getReadableDatabase();
    String sql = "Create table person(id integer primary key autoincrement,name varchar,age int)";
    db.execSQL(sql);
}
//添加数据
public  void insertData(){
    DatabaseHelper helper=new DatabaseHelper(this,"lqwvje.db");
    SQLiteDatabase db= helper.getReadableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put("name","罗分明");
    contentValues.put("age",18);
    long l= db.insert("person",null,contentValues);
    db.close();
    Log.d("id为",l+"");
    Toast.makeText(this,"id"+l,Toast.LENGTH_LONG).show();
}
//修改数据
public  void updateData(){
    DatabaseHelper helper=new DatabaseHelper(this,"lqwvje.db");
    SQLiteDatabase db= helper.getReadableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put("name","lqwvje");
    contentValues.put("age",19);
    int rows=db.update("person",contentValues,"id=?",new String[]{"1"});
    Log.d("updataData",rows+"");
}
//删除数据
public void deleteData(){
    DatabaseHelper helper=new DatabaseHelper(this,"lqwvje.db");
    SQLiteDatabase db= helper.getReadableDatabase();
    int rows=db.delete("person","id=?",new String[]{"2"});
    Log.d("deleteData",rows+"");
}
//查询数据
public  void queryData(){
    DatabaseHelper helper=new DatabaseHelper(this,"lqwvje.db");
    SQLiteDatabase db= helper.getReadableDatabase();
    Cursor cursor=db.query("person",null,null,null,null,null,null);
    if(cursor.moveToFirst()){
        do{
            String name=cursor.getString(cursor.getColumnIndex("name"));
            int age=cursor.getInt(cursor.getColumnIndex("age"));
            int id=cursor.getInt(cursor.getColumnIndex("id"));
            Log.d("queryData",name+":"+age+":id:"+id);
        }while (cursor.moveToNext());
    }
}