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

2016-02-19 10:06 10 1 收藏

给自己一点时间接受自己,爱自己,趁着下午茶的时间来学习图老师推荐的Android SQLite数据库增删改查操作的案例分析,过去的都会过去,迎接崭新的开始,释放更美好的自己。

【 tulaoshi.com - 编程语言 】

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;
    }

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)

    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.length0){
            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 ListPerson getScrollData(int startResult, int maxResult){
        ListPerson persons = new ArrayListPerson();
        //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;

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)

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());
        ListPerson 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});
    }
}

运行结果

来源:https://www.tulaoshi.com/n/20160219/1593345.html

延伸阅读
过程和函数 过程和函数都以编译后的形式存放在数据库中,函数可以没有参数也可以有多个参数并有一个返回值。过程有零个或多个参数,没有返回值。函数和过程都可以通过参数列表接收或返回零个或多个值,函数和过程的主要区别不在于返回值,而在于他们的调用方式。过程是作为一个独立执行语句调用的: pay_involume(invoice_nbr,30,du...
完整性约束 完整性约束用于增强数据的完整性,Oracle提供了5种完整性约束: Check NOT NULL Unique Primary Foreign key 完整性约束是一种规则,不占用任何数据库空间。完整性约束存在数据字典中,在执行SQL或PL/SQL期间使用。用户可以指明约束是启用的还是禁用的,当约束启用时,他增强了...
Oracle数据库数据对象中最基本的是表和视图,其他还有约束、序列、函数、存储过程、包、触发器等。对数据库的操作可以基本归结为对数据对象的操作,理解和掌握Oracle数据库对象是学习Oracle的捷径。 表和视图 Oracle中表是数据存储的基本结构。ORACLE8引入了分区表和对象表,ORACLE8i引入了临时表,使表的功能更强大。视图是一个...
标签: Web开发
insert方法 代码如下: public void insert(Object o){Session session = HibernateSessionFactory.currentSession();Transaction t = session.beginTransaction();session.save(o);t.commit();HibernateSessionFactory.clossSession();} delete方法 代码如下: public void delete(Object o,Serializable id){Session session = Hibe...
  /*******************************  * 功能:数据库操作相关  * 作者:FlashICP  * 时间:2005-7-22  * ******************************/ using System; using System.Data; using System.Data.SqlClient; using System.Web; namespace moban {  public class data  {   protected static strin...

经验教程

47

收藏

56
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部