码迷,mamicode.com
首页 > 移动开发 > 详细

Android中SQLite的使用

时间:2017-06-29 22:12:54      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:pen   抽象   创建   log   ring   help   count()   let   else   

一、如何创建数据库和表?

     自己的类继承抽象类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的使用

标签:pen   抽象   创建   log   ring   help   count()   let   else   

原文地址:http://www.cnblogs.com/drinkMilk/p/7096379.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!