Android SQLite的简单使用

1.创建DataEntity实体类

package database;

public class DataEntity {
    
    
    private Integer id;
    private String data_one;
    private Integer data_two;
    private String data_three;

    public Integer getId() {
    
    
        return id;
    }

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

    public String getData_one() {
    
    
        return data_one;
    }

    public void setData_one(String data_one) {
    
    
        this.data_one = data_one;
    }

    public Integer getData_two() {
    
    
        return data_two;
    }

    public void setData_two(Integer data_two) {
    
    
        this.data_two = data_two;
    }

    public String getData_three() {
    
    
        return data_three;
    }

    public void setData_three(String data_three) {
    
    
        this.data_three = data_three;
    }
}

2.创建DataBaseHelper类

package database;

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

public class DataBaseHelper extends SQLiteOpenHelper {
    
    
    public final static String CREATE_TABLE_SQL="create table if not exists test_data (id integer primary key autoincrement,data_one text,data_two integer,data_three text)";
    public DataBaseHelper(Context context, String name, int version) {
    
    
        super(context, name, null, version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
    
    
        //db.execSQL("drop table test_data");
        db.execSQL(CREATE_TABLE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
    

    }
}

该类需要继承SQLiteOpenHelper才行。

3.创建DataBaseService服务

package database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DataBaseService {
    
    
    private DataBaseHelper dbHelper;
    private static DataBaseService instance = null;

    public DataBaseService(Context context) {
    
    
        this.dbHelper = new DataBaseHelper(context,"data.db",1);//数据库名称
    }

    public synchronized static DataBaseService getInstance(Context ctx) {
    
    
        if (null == instance) {
    
    
            instance = new DataBaseService(ctx);
        }
        return instance;
    }

    /**
     * 新增数据
     * @param data
     */
    public void saveData(String data) {
    
    
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
    
    
            db.beginTransaction();
            ContentValues values = new ContentValues();
            values.put("data_one", data);
            values.put("data_two", 0);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = df.format(new Date());
            values.put("data_three", date);
            db.insert("test_data", null, values);
            db.setTransactionSuccessful();
        }finally {
    
    
            db.endTransaction();
        }
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public DataEntity findData(Integer id) {
    
    
        DataEntity entity = null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("test_data",null,
                "id=?", new String[] {
    
     id.toString() }, null, null,
                null, "1");
        try {
    
    
            if (cursor.moveToFirst()) {
    
    
                entity = filterEntity(cursor, entity);
                return entity;
            }
            return null;
        } finally {
    
    
            cursor.close();
        }
    }

    /**
     * 查询list
     * @param data_two
     * @return
     */
    public List<DataEntity> findDataList(String data_two, String limit) {
    
    
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("test_data",null,
                "data_two=?", new String[]{
    
    data_two}, null, null,
                null, limit);
        ArrayList<DataEntity> list = new ArrayList<>();
        try {
    
    
            while (cursor.moveToNext()) {
    
    
                DataEntity entity = new DataEntity();
                entity = filterDataEntity(cursor, entity);
                list.add(entity);
            }
        } finally {
    
    
            cursor.close();
        }
        return list;
    }
    
    /**
     * 封装实体类
     * @param cursor
     * @param entity
     * @return
     */
    private DataEntity filterDataEntity(Cursor cursor, DataEntity entity){
    
    
        Integer id = cursor.getInt(cursor.getColumnIndex("id"));
        entity.setId(id);
        String data_one = cursor.getString(cursor.getColumnIndex("data_one"));
        entity.setData_one(data_one);
        Integer data_two = cursor.getInt(cursor.getColumnIndex("data_two"));
        entity.setData_two(data_two);
        String data_three = cursor.getString(cursor.getColumnIndex("data_three"));
        entity.setData_three(data_three);
        return entity;
    }

    /**
     * 根据data_two查询数量
     * @param data_two
     * @return
     */
    public int countDataByData_two(String data_two) {
    
    
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("test_data",null,"data_two=?",
                new String[]{
    
    data_two}, null, null,null);
        return cursor.getCount();
    }


    /**
     * 查询所有数量
     * @return
     */
    public int countAllData() {
    
    
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("test_data",null,null,
                null,null, null,null);
        return cursor.getCount();
    }

    /**
     * 根据ID删除数据
     * @param ids
     * @return
     */
    public int deleteWeightDataByIds(List<Integer> ids) {
    
    
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
    
    
            db.beginTransaction();
            for (int i = 0; i < ids.size(); i++) {
    
    
                db.delete("test_data", "id=?", new String[]{
    
    String.valueOf(sids.get(i))});
            }
            db.setTransactionSuccessful();
            return 0;
        }finally {
    
    
            db.endTransaction();
        }
    }

    public void updateData_twoByIds(String data_two, List<Integer> ids) {
    
    
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
    
    
            db.beginTransaction();
            for (Integer id : ids) {
    
    
                ContentValues value = new ContentValues();
                value.put("data_two", data_two);
                db.update("test_data", value, "id=?", new String[] {
    
     String.valueOf(id) });
            }
            db.setTransactionSuccessful();
        }finally {
    
    
            db.endTransaction();
        }
    }
    
    public Cursor findTables(){
    
    
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select name from sqlite_master where type='table';", null);
        /*while(cursor.moveToNext()){
            //遍历出表名
            String name = cursor.getString(0);
        }*/
        return cursor;
    }
}

4.调用

DataBaseService service = new DataBaseService(MainActivity.this);
service.saveData(str);

5.问题说明

5.1.Cursor的方法

c.move(int offset); //以当前位置为参考,移动到指定行  
c.moveToFirst();    //移动到第一行  
c.moveToLast();     //移动到最后一行  
c.moveToPosition(int position); //移动到指定行  
c.moveToPrevious(); //移动到前一行  
c.moveToNext();     //移动到下一行  
c.isFirst();        //是否指向第一条  
c.isLast();     //是否指向最后一条  
c.isBeforeFirst();  //是否指向第一条之前  
c.isAfterLast();    //是否指向最后一条之后  
c.isNull(int columnIndex);  //指定列是否为空(列基数为0)  
c.isClosed();       //游标是否已关闭  
c.getCount();       //总数据项数  
c.getPosition();    //返回当前游标所指向的行数  
c.getColumnIndex(String columnName);//返回某列名对应的列索引值  
c.getString(int columnIndex);   //返回当前行指定列的值  

5.1.参考链接

5.2.主键自增

第二步DataBaseHelper中sql:

create table if not exists test_data (id integer primary key autoincrement,data_one text,data_two integer,data_three text

其中id integer primary key autoincrement为自增,目前sqlite只支持integer类型的自增。

5.3.使用事务

使用事务防止断电事务未提交

public void saveData(String data) {
    
    
        SQLiteDatabase db = dbHelper.getWritableDatabase();//使用读写操作才需要事务
        try {
    
    
            db.beginTransaction();//开启事务
            db.setTransactionSuccessful();//设置事务成功完成
        }finally {
    
    
            db.endTransaction();//事务完成,进行提交
        }
    }

5.4.判断表是否存在,不存在进行创建

5.4.1.方式1:

第二步DataBaseHelper中sql:

create table if not exists test_data (id integer primary key autoincrement,data_one text,data_two integer,data_three text

其中if not exists进行判断。

5.4.2.方式2:

或者

String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + dbName + "';";
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor.moveToNext()) {
    
    
        int count = cursor.getInt(0); //如果count>0则存在,否则不存在
    }

5.5. 关于程序卸载问题

只有当软件彻底卸载的时候,默认的数据库会自动被删除,如果想将数据库测地保存在系统中,需要在保存数据的时候,设置数据库数据保存的位置。

猜你喜欢

转载自blog.csdn.net/m0_37356874/article/details/103856711