安卓本地數據庫SQLite簡單使用

安卓本地數據庫SQLite簡單使用。

//創建ShopDatabaseHelper類用於創建一個新的數據庫,創建所需要的表

public class ShopDatabaseHelper extends SQLiteOpenHelper { //數據庫名 private static final String name = "shop.db"; private SQLiteDatabase db; private static final int version = 1; private Context context;
//構造方法用於創建一個新的數據庫
public ShopDatabaseHelper(Context context) { super(context, name, null, version); this.context=context; }
//創建所需要的表
@Override public void onCreate(SQLiteDatabase db) { this.db=db; db.execSQL("create table if not exists shop(id integer primary key,url varchar(100),name varchar(20),price varchar(5)) "); }
//刪除數據庫
public void deleteDb(){ context.deleteDatabase(name); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }}
//創建一個數據處理類,用於對一個表的數據的增刪查改

public class ShopService {
    ShopDatabaseHelper databaseHelper;
    SQLiteDatabase db;

    public ShopService(Context context) {
        databaseHelper = new ShopDatabaseHelper(context);
    }
//插入輸入方法,傳入表名和所要插入的數據
    public void initShop(String table, Commodity commodity) {
        db=databaseHelper.getWritableDatabase();
        ContentValues value = new ContentValues();
        value.put("name", commodity.getImages().get(0));
        db.insert("shop",null,value);
    }
// 查詢指定表的數據
public List getTable(String table){
       ArrayList list=new ArrayList<>();
       db=databaseHelper.getReadableDatabase();
       Cursor cursor=db.query(table,null,null,null,null,null,null);
       while (cursor.moveToNext()){

       }
       return  list;
   }
//更新表數據
 public   List upDataTable(String table,Commodity commodity){
       ArrayList list=new ArrayList<>();
       db=databaseHelper.getWritableDatabase();
       ContentValues contentValues=new ContentValues();
       contentValues.put("","");
       db.update(table,contentValues,"id=?",new String[]{""});
       return  list;
   }
//刪除指定的某條數據
public void delShop(String table, String id) {
    db=databaseHelper.getWritableDatabase();
    db.delete(table,"id=?",new String[]{id});
    db.close();
}

}

You May Also Like