首页 > 代码库 > 学习Android数据库SQLite的笔记

学习Android数据库SQLite的笔记

       使用SQLiteOpenHelper类操作数据库是官方提供的一个官方帮助类,操作数据库要使用到SQLiteDatabase,可以通过getReadableDatabase()或getWritableDatabase()获取,这两个方法都可以打开或创建一个数据库,不同的是当磁盘空间已满等情况造成的数据库不可写,getReadableDatabase()是可以成功打开数据库的,但只可以读取数据库,而使用getWritableDatabase()则会直接抛出异常。

首先必须创建一个继承SQLiteOpenHelper的类

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabaseHelper extends SQLiteOpenHelper {
    //创建表的SQL语句
    public static final String CREATE_STUDENT_TABLE = 
                "CREATE TABLE student (id integer primary key autoincrement,age integer, name text, number text)"; /** * 构造方法 * @param context 上下文 * @param name 数据库的名字 * @param factory 自定义一个Cursor * @param version 数据版本号 */ public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { //创建数据库 db.execSQL(CREATE_STUDENT_TABLE);
Log.e("MyDatabaseHelper","数据表已创建");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//在构造方法中的version中传进来的值比当前的数据库高,就会执行这个方法
   }
}

如果要创建一个数据库就执行下面代码,也可以使用mydbHelper.getReadableDatabase()

MyDatabaseHelper mydbHelper = new MyDatabaseHelper(this,"school",null,1);
//如果数据库存在就打开,否则就创建
SQLiteDatabase writdb = mydbHelper.getWritableDatabase();

技术分享

为了方便数据的操作,创建一个Student类

技术分享
public class Student {
    private int id;
    private String number;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "学生{" +
                "id=" + id +
                ", 学号=‘" + number + ‘\‘‘ +
                ", 姓名=‘" + name + ‘\‘‘ +
                ", 年龄=" + age +
                ‘}‘;
    }
}
View Code

插入数据

private MyDatabaseHelper mydbHelper;
private SQLiteDatabase writdb;

mydbHelper = new MyDatabaseHelper(this,"school",null,1);
writdb = mydbHelper.getWritableDatabase();

Student insertStu = new Student();
insertStu.setNumber("1238409");
insertStu.setName("小明");
insertStu.setAge(21);

//获取数据
ContentValues cv = new ContentValues();
cv.put("number",insertStu.getNumber());
cv.put("name",insertStu.getName());
cv.put("age",insertStu.getAge());
//向数据库插入数据
writdb.insert("student",null,cv);
/**
 * SQL语句方式
 * writdb.execSQL("insert into student(number,name,age) values(?,?,?)",
 *                   new String[]{insertStu.getNumber(), insertStu.getName(), String.valueOf(insertStu.getAge())});
 */

writdb.close();
mydbHelper.close();

查询数据

private MyDatabaseHelper mydbHelper;
private SQLiteDatabase writdb;

mydbHelper = new MyDatabaseHelper(this,"school",null,1);
writdb = mydbHelper.getWritableDatabase();
//创建一个集合用于存放查询到的数据
List<Student> students2 = new ArrayList<>();

//参数说明:①表名(使用全局常量,避免写错),②要查找的列名,③约束条件,④约束条件的值,⑤分组,⑥分组后的约束,⑦排序
Cursor cursor = writdb.query("student",null,null,null,null,null,null);
/**
 * SQL语句方式
 * Cursor cursor = writdb.rawQuery("select * from student", null);
 */

if (cursor != null) {
    while (cursor.moveToNext()) {
        Student stu = new Student();
        //获取一行中的数据
        stu.setId(cursor.getInt(cursor.getColumnIndex("id")));
        stu.setNumber(cursor.getString(cursor.getColumnIndex("number")));
        stu.setName(cursor.getString(cursor.getColumnIndex("name")));
        stu.setAge(cursor.getInt(cursor.getColumnIndex("age")));
        //添加到集合里
        students2.add(stu);
    }
    //记得关闭
    cursor.close();
}

writdb.close();
mydbHelper.close();
for (Student student2 : students2) {
    Log.e("查询结果", student2.toString()); 
}    

插入了3条数据

技术分享

更新数据

private MyDatabaseHelper mydbHelper;
private SQLiteDatabase writdb;

mydbHelper = new MyDatabaseHelper(this, "school", null, 1);
writdb = mydbHelper.getWritableDatabase();

Student updatetStu = new Student();
updatetStu.setNumber("11111");
updatetStu.setAge(32);

//获取要更新的数据
ContentValues cv = new ContentValues();
cv.put("number",updatetStu.getNumber());
cv.put("age",updatetStu.getAge());
//参数说明:①表名,②更新的数据,③条件,④条件值
writdb.update("student",cv,"id > ?",new String[]{"1"});
/**
 * SQL语句方式
 * writdb.execSQL("update student set number = ?,age = ? where id > ?",
 *                  new String[]{updatetStu.getNumber(), String.valueOf(updatetStu.getAge()),"1"});
 */

writdb.close();
mydbHelper.close();

更新后的结果

技术分享

删除数据

private MyDatabaseHelper mydbHelper;
private SQLiteDatabase writdb;

mydbHelper = new MyDatabaseHelper(this, "school", null, 1);
writdb = mydbHelper.getWritableDatabase();

//参数说明:①表名,②条件,③条件值
writdb.delete("student","id = ?", new String[]{"2"});
/**
 * SQL语句方式
 * writdb.execSQL("delete from student where id = ?",new String[]{"2"});
 */
writdb.close(); mydbHelper.close();

删除后的结果

技术分享

 

学习Android数据库SQLite的笔记