前言
今天主要讲讲sqlite在android中的创建,存储 和 sqlite的增删改查。
下面以一个例子做讲解
一 创建数据库,需要继承SQLiteOpenHelper
下面是创建user数据库的类DBOpenHelper
package com.example.pei.textdemo.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Title:创建数据库
* Description:
* <p>
* Created by pei
* Date: 2017/11/16
*/
public class DBOpenHelper extends SQLiteOpenHelper{
private static final String DB_NAME = "test_demo.db";//数据库文件名
private static SQLiteDatabase INSTANCE;
private Context mContext;
public SQLiteDatabase getInstance() {
if (INSTANCE == null) {
INSTANCE = new DBOpenHelper(mContext).getWritableDatabase();
}
return INSTANCE;
}
public DBOpenHelper(Context context) {
this(context, DB_NAME, null, 1);
this.mContext=context;
}
public DBOpenHelper(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 user(_id integer NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
" name text,\n" +
" sex text,\n" +
" age integer);";
//创建表
db.execSQL(createTable);
}
//当数据库的版本发生变化的时候会自动执行,禁止人为调用
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
二 提供一个数据库增删改查的抽象类,主要用来统一管理整个数据库涉及到的增删改查
下面是提供增删改查抽象类DBHelper
package com.example.pei.textdemo.sqlite;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.pei.textdemo.app.AppContext;
import java.util.List;
/**
* Title:数据库增删改查帮助类
* Description:
* <p>
* Created by pei
* Date: 2017/11/16
*/
public abstract class DBHelper {
protected DBOpenHelper mDBOpenHelper;
/**获取数据库对象**/
protected SQLiteDatabase getDateBase(){
mDBOpenHelper=new DBOpenHelper(AppContext.getInstance());
return mDBOpenHelper.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 insert(Object obj);
/**删除**/
protected abstract void delete(Object obj);
/**更新**/
protected abstract void update(Object obj);
}
三 提供一个装处理数据的对象
下面是对象person的代码,很简单,就提供了些基本的set,get方法
package com.example.pei.textdemo.sqlite;
import com.example.pei.textdemo.models.BaseModel;
/**
* Title:
* Description:
* <p>
* 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需要继承的baseModel类
baseModel主要有两个作用:
- 1 实现Serializable接口,方便数据的有序化
- 2 提供 objectToString 方法,作用是将一个对象中所有属性都显示出来,其实就是方便我打印log啦
下面是 baseModel 代码
package com.example.pei.textdemo.models;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Title:
* Description:
* <p>
* Created by pei
* Date: 2017/10/30
*/
public class BaseModel implements Serializable{
/**打印对象属性值**/
public String objectToString(Object obj){
List<Map<String,Object>>FiledInfos=getFiledsInfo(obj);
StringBuffer buffer=new StringBuffer();
if(!FiledInfos.isEmpty()){
for(Map<String,Object>map:FiledInfos){
String tag=map.get("name").toString();
if(!"$change".equals(tag)&&!"serialVersionUID".equals(tag)){
String str=map.get("name")+"="+map.get("value")+" ";
buffer.append(str);
}
}
}else{
if(obj!=null){
String className=obj.getClass().getSimpleName();
buffer.append(className);
}else{
buffer.append("objectToString方法调用参数为null");
}
}
return buffer.toString();
}
/**
* 获取属性类型(type),属性名(name),属性值(value)的map组成的list
*/
private List getFiledsInfo(Object obj){
List<Map<String,Object>>list=new ArrayList();
if(obj!=null) {
Field fields[] = obj.getClass().getDeclaredFields();
String fieldNames[] = new String[fields.length];
Map mapInfo = null;
for (int i = 0; i < fields.length; i++) {
Object o = getFieldValueByName(fields[i].getName(), obj);
mapInfo = new HashMap();
mapInfo.put("type", fields[i].getType().toString());
mapInfo.put("name", fields[i].getName());
mapInfo.put("value", getFieldValueByName(fields[i].getName(), obj));
list.add(mapInfo);
}
}
return list;
}
/**
* 根据属性名获取属性值
*/
private Object getFieldValueByName(String fieldName,Object obj){
Object value=null;
try {
String firstLetter=fieldName.substring(0,1).toUpperCase();
String getter="get" +firstLetter+fieldName.substring(1);
Method method=obj.getClass().getMethod(getter,new Class[] {});
value = method.invoke(obj, new Object[] {});
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return value;
}
/**
* 获取属性名数组
*/
private String[] getFiledName(Object obj){
Field fields[]=obj.getClass().getDeclaredFields();
String fieldNames[]=new String[fields.length];
for(int i=0;i<fields.length;i++){
fieldNames[i]=fields[i].getName();
}
return fieldNames;
}
/***
* 获取对象的所有属性值,返回一个对象数组
*/
private Object[] getFiledValues(Object obj){
String fieldNames[]=this.getFiledName(obj);
Object value[]=new Object[fieldNames.length];
for(int i=0;i<fieldNames.length;i++){
value[i]=this.getFieldValueByName(fieldNames[i],obj);
}
return value;
}
}
五 提供具体的增删改查类UserDBHelper
此类需要继承抽象类DBHelper,在activity中涉及到增删改查时,基本是调用这个类中的方法
package com.example.pei.textdemo.sqlite;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.List;
/**
* Title:
* Description:
* <p>
* Created by pei
* Date: 2017/11/16
*/
public class UserDBHelper extends DBHelper{
private UserDBHelper() {
}
private static class Holder {
private static UserDBHelper instance = new UserDBHelper();
}
public static UserDBHelper getInstance() {
return Holder.instance;
}
@Override
protected List<Person> checkAll() {
List<Person> list = new ArrayList<>();
//COLLATE NOCASE 忽略大小写查询
// Cursor cursor = getDateBase().rawQuery("select * from T_cpz where isqy='True' COLLATE NOCASE;", null);
Cursor cursor = getDateBase().rawQuery("select * from user", null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
int age=cursor.getInt(cursor.getColumnIndex("age"));
Person person=new Person();
person.setName(name);
person.setSex(sex);
person.setAge(age);
list.add(person);
}
cursor.close();
return list;
}
@Override
protected void insert(Object obj){
Person person= (Person) obj;
String sql="INSERT INTO user(name,sex,age) VALUES('"+ person.getName()+"','"+ person.getSex()+"','"+ person.getAge()+"');";
getDateBase().execSQL(sql);
}
@Override
protected void delete(Object obj) {
Person person = (Person) obj;
String sql = "DELETE FROM user WHERE name='" + person.getName() + "';";
getDateBase().execSQL(sql);
}
@Override
protected void update(Object obj) {
Person person = (Person) obj;
String sql="UPDATE user SET age="+person.getAge()+" WHERE name='"+person.getName()+"';";
getDateBase().execSQL(sql);
}
}
六 下面看看在activity中涉及到的具体数据的处理
此处只显示一些增删改查的代码,仅做范例
// //添加
// Person person=new Person();
// person.setName("大和");
// person.setSex("男");
// person.setAge(28);
// Person person1=new Person();
// person1.setName("红豆");
// person1.setSex("女");
// person1.setAge(26);
// UserDBHelper.getInstance().insert(person);
// UserDBHelper.getInstance().insert(person1);
// List<Person> persons=UserDBHelper.getInstance().checkAll();
// for(Person p:persons){
// LogUtil.e(SqliteActivity.class,"===p="+p.objectToString(p));
// }
// //更新
// Person updatePerson = new Person();
// updatePerson.setName("大和");
// updatePerson.setSex("男");
// updatePerson.setAge(30);
// UserDBHelper.getInstance().update(updatePerson);
// List<Person> persons = UserDBHelper.getInstance().checkAll();
// for (Person p : persons) {
// LogUtil.e(SqliteActivity.class, "===p=" + p.objectToString(p));
// }
// //删除
// Person deletePerson = new Person();
// deletePerson.setName("大和");
// deletePerson.setSex("男");
// deletePerson.setAge(30);
// UserDBHelper.getInstance().delete(deletePerson);
// List<Person> persons = UserDBHelper.getInstance().checkAll();
// for (Person p : persons) {
// LogUtil.e(SqliteActivity.class, "===p=" + p.objectToString(p));
// }
//查询所有
List<Person> persons = UserDBHelper.getInstance().checkAll();
for (Person p : persons) {
LogUtil.e(SqliteActivity.class, "===p=" + p.objectToString(p));
}
ok,今天只是对android数据库的一个简单讲解了,具体到项目中运用的时候,我们还需要对以上 helper类做针对性的修改
谢谢诶!
网友评论