前言
sqliteDataBase能存储的数据类型有:
1.NULL:空值。
2.INTEGER:带符号的整型,具体取决有存入数字的范围大小。
3.REAL:浮点数字,存储为8-byte IEEE浮点数。
4.TEXT:字符串文本。
5.BLOB:二进制对象。
下面就来用一个例子讲讲sqlite存储对象。
一.先抛出一个model,类名为Person,代码如下:
package com.example.pei.textdemo.sqlite;
import com.example.pei.textdemo.models.BaseModel;
/**
* Title:
* Description:
*
* Created by pei
* Date: 2017/11/16
*/
public class Person extends BaseModel {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
这个类很简单,注意的是Person需要实现 Serializable接口,方便序列化,大家如果对以上代码中BaseModel有疑问的话,可以看看我的文章SQLiteDatabase学习(二),这里就不做介绍了
二.写创建数据库的类ObjectOpenHelper
ObjectOpenHelper需要继承SQLiteOpenHelper,然后在创建数据表person的时候,Person会对应表中的data字段,data数据类型为 BLOB,具体代码如下:
package com.example.pei.textdemo.sqlite_object;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Title:
* Description:
*
* Created by pei
* Date: 2017/11/22
*/
public class ObjectOpenHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "save_object.db";//数据库文件名
private static SQLiteDatabase INSTANCE;
private Context mContext;
public SQLiteDatabase getInstance() {
if (INSTANCE == null) {
INSTANCE = new ObjectOpenHelper(mContext).getWritableDatabase();
}
return INSTANCE;
}
public ObjectOpenHelper(Context context) {
this(context, DB_NAME, null, 1);
this.mContext=context;
}
public ObjectOpenHelper(Context context, String dbName, SQLiteDatabase.CursorFactory factory, int version) {
super(context, dbName, factory, version);
}
//首次创建数据库时调用,一般进行建库建表操作
@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE IF NOT EXISTS person(_id integer NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
" data BLOB);";
//创建表
db.execSQL(createTable);
}
//当数据库的版本发生变化的时候会自动执行,禁止人为调用
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
三.编写数据库的抽象管理类ObjectDBHepler
代码如下:
package com.example.pei.textdemo.sqlite_object;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.pei.textdemo.app.AppContext;
import java.util.List;
/**
* Title:
* Description:
*
* Created by pei
* Date: 2017/11/22
*/
public abstract class ObjectDBHepler {
protected ObjectOpenHelper mObjectOpenHelper;
private ObjectOpenHelper getObjectDBHelper(){
if(mObjectOpenHelper==null){
mObjectOpenHelper=new ObjectOpenHelper(AppContext.getInstance());
}
return mObjectOpenHelper;
}
/**获取数据库对象**/
protected SQLiteDatabase getDateBase(){
return getObjectDBHelper().getInstance();
}
/**关闭数据库**/
protected void closeDB(){
SQLiteDatabase db = getDateBase();
if(db!=null){
db.close();
}
}
/**
* 判断表是否存在
* @param tableName:表名
* @return
*/
protected boolean isTableExist(String tableName){
Cursor cursor = getDateBase().rawQuery("select name from sqlite_master where type='table';", null);
while(cursor.moveToNext()){
//遍历出表名
String name = cursor.getString(0);
if(name.equals(tableName)){
return true;
}
}
return false;
}
/**查询**/
protected abstract List> checkAll();
/**添加**/
protected abstract void insertObject(T t);
/**删除**/
protected abstract void delete(Object obj);
/**更新**/
protected abstract void update(Object obj);
}
四.实现数据的增删改查类ObjUserHelper,此类需要继承ObjectDBHepler,然后在activity中会调用
package com.example.pei.textdemo.sqlite_object;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.pei.textdemo.sqlite.Person;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Title:
* Description:
*
* Created by pei
* Date: 2017/11/22
*/
public class ObjUserHelper extends ObjectDBHepler{
private ObjUserHelper() {
}
private static class Holder {
private static ObjUserHelper instance = new ObjUserHelper();
}
public static ObjUserHelper getInstance() {
return ObjUserHelper.Holder.instance;
}
@Override
protected List> checkAll() {
Listlist=new ArrayList<>();
SQLiteDatabase database = getDateBase();
Cursor cursor = database.rawQuery("select * from person", null);
if (cursor != null) {
while (cursor.moveToNext()) {
byte data[] = cursor.getBlob(cursor.getColumnIndex("data"));
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(data);
try {
ObjectInputStream inputStream = new ObjectInputStream(arrayInputStream);
Person person = (Person) inputStream.readObject();
inputStream.close();
arrayInputStream.close();
list.add(person);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
cursor.close();
}
return list;
}
@Override
protected void insertObject(T t) {
Person person= (Person) t;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(arrayOutputStream);
objectOutputStream.writeObject(person);
objectOutputStream.flush();
byte data[] = arrayOutputStream.toByteArray();
objectOutputStream.close();
arrayOutputStream.close();
SQLiteDatabase database = getDateBase();
String sql="insert into person(data) values (?)";
database.execSQL(sql,new Object[]{ data });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void delete(Object obj) {
}
@Override
protected void update(Object obj) {
}
}
五.在MainActivity中的调用
Person p=new Person();
p.setAge(25);
p.setName("展昭");
p.setSex("nan");
ObjUserHelper.getInstance().insertObject(p);
LogUtil.e(SqliteObjectActivity.class,"====save success====");
Listpersons= (List) ObjUserHelper.getInstance().checkAll();
if(persons.isEmpty()){
LogUtil.e(SqliteObjectActivity.class,"=====persons is null=====");
}else{
for(Person pt:persons){
LogUtil.e(SqliteObjectActivity.class,"=====pt=="+pt.objectToString(pt));
}
}
最后看看运行的结果:
ok,关于sqlite就讲到这里了,谢谢。