Android中SQLite的使用
一、如何创建数据库和表?
自己的类继承抽象类SQLiteOpenHelper。
(1)修改中的构造方法中的super方法创建数据库
(2)第一个抽象方法用于创建表
二、如何进行增删改查,代码如下:
public class StudentDao { private StudentSqliteOpenHelper studentSqliteOpenHelper; public StudentDao(Context context){ studentSqliteOpenHelper = new StudentSqliteOpenHelper(context); } //增 public boolean add(Student student){ SQLiteDatabase db = studentSqliteOpenHelper.getReadableDatabase(); ContentValues values = new ContentValues(); values.put("name",student.name); values.put("age",student.age); values.put("school",student.school); long result = db.insert("student", null, values); db.close(); if(result != -1){ return true; }else{ return false; } } //删 public int del(String name){ SQLiteDatabase db = studentSqliteOpenHelper.getReadableDatabase(); int delLines = db.delete("student", "name = ?", new String[]{name}); db.close(); return delLines; } //改 public int update(Student student){ SQLiteDatabase db = studentSqliteOpenHelper.getReadableDatabase(); ContentValues values = new ContentValues(); values.put("name",student.name); values.put("age",student.age); values.put("school",student.school); int result = db.update("student", values, "name = ?", new String[]{student.name}); db.close(); return result; } //查 public ArrayList<Student> query(String name){ SQLiteDatabase db = studentSqliteOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from student where name = ?", new String[]{name}); ArrayList<Student> arrayList = new ArrayList<>(); if(cursor != null && cursor.getCount() > 0){ //遍历cursor while (cursor.moveToNext()){ Student s = new Student(); s.id = cursor.getLong(0); s.name = cursor.getString(1); s.age = cursor.getInt(2); s.school = cursor.getString(3); arrayList.add(s); } } db.close(); return arrayList; } }