首页 > 代码库 > Android中SQLite的使用
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的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。