//创建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<String> getTable(String table){ ArrayList<String> list=new ArrayList<>(); db=databaseHelper.getReadableDatabase(); Cursor cursor=db.query(table,null,null,null,null,null,null); while (cursor.moveToNext()){ } return list; } //更新表数据 public List<String> upDataTable(String table,Commodity commodity){ ArrayList<String> 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(); }}
安卓本地数据库SQLite简单使用
最新推荐文章于 2024-06-06 21:12:11 发布