Android SQLite数据库增删改查操作的案例分析

时间:2022-06-06 02:55:03 

Person实体类


package com.ljq.domain;


public class Person {
    private Integer id;
    private String name;
    private String phone;

    public Person() {
        super();
    }

    public Person(String name, String phone) {
        super();
        this.name = name;
        this.phone = phone;
    }

    public Person(Integer id, String name, String phone) {
        super();
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

}

DBOpenHelper数据库关联类


package com.ljq.db;

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

public class DBOpenHelper extends SQLiteOpenHelper {
    // 类没有实例化,是不能用作父类构造器的参数,必须声明为静态
    private static final String DBNAME = "ljq.db";
    private static final int VERSION = 1;

    // 第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,
    // 设置为null,代表使用系统默认的工厂类
    public DBOpenHelper(Context context) {
        super(context, DBNAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE PERSON (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME VARCHAR(20), PHONE VARCHAR(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 注:生产环境上不能做删除操作
        db.execSQL("DROP TABLE IF EXISTS PERSON");
        onCreate(db);
    }
}

PersonService业务类


package com.ljq.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;

import com.ljq.domain.Person;

public class PersonService {
    private DBOpenHelper dbOpenHelper = null;

    /**
     * 构造函数
     *
     * 调用getWritableDatabase()或getReadableDatabase()方法后,会缓存SQLiteDatabase实例;
     * 因为这里是手机应用程序,一般只有一个用户访问数据库,所以建议不关闭数据库,保持连接状态。
     * getWritableDatabase(),getReadableDatabase的区别是当数据库写满时,调用前者会报错,调用后者不会,
     * 所以如果不是更新数据库的话,最好调用后者来获得数据库连接。
     *
     * 对于熟悉SQL语句的程序员最好使用exeSQL(),rawQuery(),因为比较直观明了
     *
     * @param context
     */
    public PersonService(Context context){
        dbOpenHelper = new DBOpenHelper(context);
    }

    public void save(Person person){
        dbOpenHelper.getWritableDatabase().execSQL("insert into person(name, phone) values (?, ?)",
                new Object[]{person.getName(), person.getPhone()});
    }

    public void update(Person person){
        dbOpenHelper.getWritableDatabase().execSQL("update person set name=?, phone=? where id=?",
                new Object[]{person.getName(), person.getPhone(), person.getId()});
    }

    public void delete(Integer... ids){
        if(ids.length>0){
            StringBuffer sb = new StringBuffer();
            for(Integer id : ids){
                sb.append("?").append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            dbOpenHelper.getWritableDatabase().execSQL("delete from person where id in ("+sb+")", (Object[])ids);
        }
    }

    public Person find(Integer id){
        Cursor cursor = dbOpenHelper.getReadableDatabase().rawQuery("select id, name, phone from person where id=?",
                new String[]{String.valueOf(id)});
        if(cursor.moveToNext()){
            int personid = cursor.getInt(0);
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            return new Person(personid, name, phone);
        }
        return null;
    }

    public long getCount(){
        Cursor cursor = dbOpenHelper.getReadableDatabase().query("person",
                new String[]{"count(*)"}, null,null,null,null,null);
        if(cursor.moveToNext()){
            return cursor.getLong(0);
        }
        return 0;
    }

    /**
     * 分页
     *
     * @param startResult 偏移量,默认从0开始
     * @param maxResult 每页显示的条数
     * @return
     */
    public List<Person> getScrollData(int startResult, int maxResult){
        List<Person> persons = new ArrayList<Person>();
        //Cursor cursor = dbOpenHelper.getReadableDatabase().query("person", new String[]{"id, name, phone"},
        //        "name like ?", new String[]{"%ljq%"}, null, null, "id desc", "1,2");
        Cursor cursor = dbOpenHelper.getReadableDatabase().rawQuery("select * from person limit ?,?",
                new String[]{String.valueOf(startResult), String.valueOf(maxResult)});
        while(cursor.moveToNext()) {
            int personid = cursor.getInt(0);
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            persons.add(new Person(personid, name, phone));
        }
        return persons;
    }

   

}

PersonServiceTest测试类


package com.ljq.test;

import java.util.List;

import com.ljq.db.PersonService;
import com.ljq.domain.Person;

import android.test.AndroidTestCase;
import android.util.Log;

public class PersonServiceTest extends AndroidTestCase{
    private final String TAG = "PersonServiceTest";

    public void testSave() throws Exception{
        PersonService personService = new PersonService(this.getContext());
        personService.save(new Person("zhangsan1", "059188893343"));
        personService.save(new Person("zhangsan2", "059188893343"));
        personService.save(new Person("zhangsan3", "059188893343"));
        personService.save(new Person("zhangsan4", "059188893343"));
        personService.save(new Person("zhangsan5", "059188893343"));
    }

    public void testUpdate() throws Exception{
        PersonService personService = new PersonService(this.getContext());
        Person person = personService.find(1);
        person.setName("linjiqin");
        personService.update(person);
    }

    public void testFind() throws Exception{
        PersonService personService = new PersonService(this.getContext());
        Person person = personService.find(1);
        Log.i(TAG, person.getName());
    }

    public void testList() throws Exception{
        PersonService personService = new PersonService(this.getContext());
        List<Person> persons = personService.getScrollData(0, 10);
        for(Person person : persons){
            Log.i(TAG, person.getId() + " : " + person.getName());
        }
    }

    public void testCount() throws Exception{
        PersonService personService = new PersonService(this.getContext());
        Log.i(TAG, String.valueOf(personService.getCount()));
    }

    public void testDelete() throws Exception{
        PersonService personService = new PersonService(this.getContext());
        personService.delete(1);
    }

    public void testDeleteMore() throws Exception{
        PersonService personService = new PersonService(this.getContext());
        personService.delete(new Integer[]{2, 5, 6});
    }
}

运行结果

Android SQLite数据库增删改查操作的案例分析

标签:android,sqlite
0
投稿

猜你喜欢

  • C#委托与事件初探

    2021-06-07 00:09:42
  • 详解如何让Spring MVC显示自定义的404 Not Found页面

    2023-12-12 15:48:47
  • C#集合之可观察集合的用法

    2022-02-16 13:43:13
  • Mybatis省略@Param注解原理分析

    2023-06-19 16:08:44
  • 详解在Spring中如何自动创建代理

    2023-11-15 15:28:52
  • Java排序算法总结之希尔排序

    2022-07-16 13:19:11
  • Android实现清除单个域名的cookie

    2021-10-09 01:57:52
  • Android判断包名和类名是否存在的方法

    2021-09-23 02:52:52
  • C#使用HttpClient的正确方式你了解吗

    2023-07-04 12:12:40
  • elasticsearch数据信息索引操作action support示例分析

    2022-03-18 02:09:07
  • 基于Android LayoutInflater的使用介绍

    2023-12-22 23:50:03
  • Apache和Tomcat有什么区别_动力节点Java学院整理

    2023-08-15 08:49:44
  • spring boot容器启动流程

    2023-02-17 09:25:36
  • 浅谈Android中使用异步线程更新UI视图的几种方法

    2022-10-17 02:57:38
  • Android注解基础介绍快速入门与解读

    2023-04-30 22:32:19
  • C#画笔Pen绘制自定义线的帽子

    2022-01-09 20:33:55
  • java教学笔记之对象的创建与销毁

    2023-08-14 02:00:39
  • 使用java代码获取新浪微博应用的access token代码实例

    2023-12-01 20:18:30
  • Java字母加数字组合比较大小

    2023-02-27 15:27:52
  • C#读写xml文件方法总结(超详细!)

    2023-11-23 13:16:40
  • asp之家 软件编程 m.aspxhome.com