Android中SQLite的使用
Posted drinkMilk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } }
以上是关于Android中SQLite的使用的主要内容,如果未能解决你的问题,请参考以下文章
java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.database.sqlite异常(代码片段
当sqlite android片段中的数据更改或删除时如何刷新recyclerview?
如何在片段内的 recylerview 列表中显示 SQLite 数据库数据?