创建数据库{
创建类继承SQLiteOpenHelper
![](https://i-blog.csdnimg.cn/blog_migrate/04c61bfd52180bb9ffe2304d8a0f69dd.png)
数据库增删改查
1.获取数据库
![](https://i-blog.csdnimg.cn/blog_migrate/92fcc76f35ad14e1ef093cb4c71461c1.png)
增
//方式一
sqLiteDatabase.execSQL("insert into stu values(?,?,?)",new String[]{null,"魏帅250","20"});
sqLiteDatabase.execSQL("insert into stu values(?,?,?)",new String[]{null,"乔鑫250","30"});
sqLiteDatabase.execSQL("insert into stu values(?,?,?)",new String[]{null,"胡育嘉250","40"});
//方式二
ContentValues contentValues = new ContentValues();
contentValues.put("name","魏帅");
contentValues.put("age",21);
sqLiteDatabase.insert("stu",null,contentValues);
删
//方式一
sqLiteDatabase.execSQL("delete from stu where name = ?",new String[]{"胡育嘉250"});
//方式二
sqLiteDatabase.delete("stu","name=?",new String[]{"魏帅"});
改
//方式一
sqLiteDatabase.execSQL("update stu set age = ? where name = ?",new String[]{"250","乔鑫250"});
//方式二
ContentValues contentValues = new ContentValues();
contentValues.put("age",12);
sqLiteDatabase.update("stu",contentValues,"name=?",new String[]{"魏帅"});
查
//方式一
Cursor cursor = sqLiteDatabase.rawQuery("select * from stu",null);
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.i("--a",id+name+age);
}
//方式二
Cursor cursor = sqLiteDatabase.query("stu",null,null,null,null,null,null);
模糊查询-select * from music where title like ?",new String[]{"%烤%"}
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.i("--a",id+name+age);
}
事务处理数据
sqLiteDatabase.beginTransaction();
for (int i=0;i<30;i++){
ContentValues contentValues = new ContentValues();
contentValues.put("name","乔鑫");
contentValues.put("age",20+i);
sqLiteDatabase.insert("stu",null,contentValues);
}
sqLiteDatabase.setTransactionSuccessful();
sqLiteDatabase.endTransaction();
懒汉模式
![](https://i-blog.csdnimg.cn/blog_migrate/b6017712b01f36caca4035443135679d.png)
}