SQLite 简介
SQLite 是一款内置到移动设备上的轻量型的数据库,多用于嵌入式系统中。
数据库的使用
SQLiteOpenHelper 是 Android 提供的一个抽象工具类,负责管理数据库的创建、打开、升级工作。如果我们想创建数据库,就需要自定义一个类继承 SQLiteOpenHelper,然后重写其中的抽象方法。
1,创建SQLiteOpenHelper的实现类
public class StudentDataOpenHelper extends SQLiteOpenHelper{
/**
*param context:上下文
*param info.db:数据库的名称
*param null:默认游标工厂从数据库的头部开始读取
*param 1:数据库的版本
**/
public StudentDataOpenHelper(Context context) {
super(context, "info.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table student(_id integer primary key autoincrement,name varchar(20),sex varchar(10))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
2,创建一个工具类,提供数据库的增删改查方法
//当调用getWritableDatabase或getReadableDatabase时数据库才会被创建
public class StudentDao {
private StudentDataOpenHelper helper;
public StudentDao(Context context) {
helper = new StudentDataOpenHelper(context);
}
//添加一个学生的姓名和性别,因为id是自动增长的,所以不操作
public void add(String name,String sex){
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("insert into student (name,sex) values(?,?)",new Object[]{name,sex});
db.close();
}
//删除一个学生信息,用姓名进行删除
public void delete(String name){
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("delete from student where name = ?",new Object[]{name});
db.close();
}
//修改一个学生的性别
public void update(String name,String sex){
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("update student set set = ? where name= ?",new Object[]{name,sex});
db.close();
}
//查询一个学生的性别
public String select(String name){
String sex = null;
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select sex from student where name = ?",new String[]{name});
boolean result = cursor.moveToNext();
if (result) {
sex = cursor.getString(0);
}
db.close();
cursor.close();
return sex;
}
//查询所有同学的信息
public List<Student> findAll(){
List<Student> list = new ArrayList<Student>();
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select name,sex from student", null);
while (cursor.moveToNext()) {
String name = cursor.getString(0);
String sex = cursor.getString(1);
Student student = new Student();
student.setName(name);
student.setSex(sex);
list.add(student);
}
cursor.close();
db.close();
return list;
}
}
3,代码中使用
sd = new StudentDao(this);
sd.add(name,sex);
4,刷新Listview的界面
if (apdate == null) {
apdate = new MyApdate();
lv.setAdapter(apdate);
}else {
//通知适配器更新数据,而不是从new出来新的适配器
apdate.notifyDataSetChanged();
}
使用提供的API实现数据的增删改查
/*添加一个学生的姓名和性别,因为id是自动增长的,所以不操作
* 返回值result表示添加到数据的哪一行,返回-1表示失败
* */
public long add(String name,String sex){
SQLiteDatabase db = helper.getWritableDatabase();
//1,db.execSQL("insert into student (name,sex) values(?,?)",new Object[]{name,sex});
ContentValues values = new ContentValues();
values.put("name", name);
values.put("sex", sex);
//当nullColumnHack为空时,表格中以NULL出现
// db.insert(table, nullColumnHack, values);
long result = db.insert("student", null, values);
db.close();
return result;
}
/*删除一个学生信息,用姓名进行删除
* result代表删除了几行,0代表删除失败*/
public int delete(String name){
SQLiteDatabase db = helper.getWritableDatabase();
//db.execSQL("delete from student where name = ?",new Object[]{name});
// db.delete(table, whereClause, whereArgs)
int result = db.delete("student", "name = ?", new String[]{name});
db.close();
return result;
}
//修改一个学生的性别,result表示更新了几行,0表示更新失败
public int update(String name,String sex){
SQLiteDatabase db = helper.getWritableDatabase();
//db.execSQL("update student set set = ? where name= ?",new Object[]{name,sex});
// db.update(table, values, whereClause, whereArgs)
ContentValues values = new ContentValues();
values.put("sex", sex);
int result = db.update("student", values, "name= ?", new String[]{name});
db.close();
return result;
}
//查询一个学生的性别
public String select(String name){
String sex = null;
SQLiteDatabase db = helper.getReadableDatabase();
//Cursor cursor = db.rawQuery("select sex from student where name = ?",new String[]{name});
// db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
Cursor cursor = db.query("student", new String[]{"sex"}, "name = ?", new String[]{name}, null, null, null);
boolean result = cursor.moveToNext();
if (result) {
sex = cursor.getString(0);
}
db.close();
cursor.close();
return sex;
}
//查询所有同学的信息
public List<Student> findAll(){
List<Student> list = new ArrayList<Student>();
SQLiteDatabase db = helper.getReadableDatabase();
//Cursor cursor = db.rawQuery("select name,sex from student", null);
// db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
Cursor cursor = db.query("student", new String[]{"name","sex"}, null, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(0);
String sex = cursor.getString(1);
Student student = new Student();
student.setName(name);
student.setSex(sex);
list.add(student);
}
cursor.close();
db.close();
return list;
}
}
两种对数据库操作的实现
1,SQL语句
增
insert into student (name, phone) values (‘张三’, ‘110’)
删
delete from student where name=‘张三’
改
update student set phone=‘119’ where name=‘张三’
查
select * from student where name=‘张三’
2,使用特有 API 实现,系统帮我们组拼sql语句,优点:1.不容易拼错sql语句;2.有返回值,可以判断是否执行成功
//增
db.insert("student", null, values);
//删
db.delete("student", "name=?", new String[]{name});
//改
db.update("student", values, "name=?", new String[]{name});
//查
db.query("student", new String[]{"sex"}, "name=?", new String[]{name}, null, null, null);
数据库的事务
SQLiteDatabase提供的beginTransaction()打开事务,endTransaction()结束事务。注意:结束事务并不代表事务提交,如果想让数据写入的数据库需要在结束事务前执行 setTransactionSuccessful()方法。这是事务提交的唯一方式。
BankDBOpenHelper helper = new BankDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction(); //1.开启事务
try {
// 模拟转账的操作
db.execSQL("update account set money=money-100 where name='zhangsan'");
db.execSQL("update account set money=money+100 where name='lisi'");
db.setTransactionSuccessful();//2.设置事务执行成功
} finally {
db.endTransaction();//3.结束事务
}
db.close();