接着介绍,今天我们来介绍Sqlitedatabase的辅助类SqliteOpenHelper。一个抽象类,主要 对数据库的创建和版本的更新。至于该怎么使用? 这还用说,直接建一个类继承SqliteOpenHelper, 然后我们就能愉快的玩耍了。
/** *本类主要用于数据库的创建和表的生成以及数据库版本的更新 */ public class DbOpenHelper extends SQLiteOpenHelper { private String sql = "create table if not exists student(_id integer primary key autoincrement,name text not null,sex text not null)"; //在构造函数中创建person.db数据库 public DbOpenHelper(Context context) { super(context, "person.db",null,1); } /* 在oncreate中创建student表 此方法在第一次创建对象的时候调用 */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL(sql); } /* 当数据库版本更新的时候,调用此方法 一般是在表中修改字段名称时使用 在android中sql的使用持添加字段,但不支持修改字段名称,这算是一个坑吧 */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(newVersion>oldVersion){ //删除旧表,创建新表 } } }
package qjdt.iwintrue.com.imageloaderdemoapplication.sqlutils; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; /** * 创建数据库管理类,用于执行数据库的增、删、改、查方法 */ public class SqlUtils { private static DbOpenHelper helper; private static SQLiteDatabase db; public DbOpenHelper getDbHelper(Context context){ if(helper == null){ synchronized (SqlUtils.class){ if(helper == null){ helper = new DbOpenHelper(context); //这两个方法都可以获取SQLiteDatabase 实例,但是要注意的是, //当内存满了再调用getWritableDatabase()方法会出错,getReadableDatabase()方法是以 //读写方式打开数据库,当内存满了就会以只读的方式打开数据库,不会报错 db = helper.getReadableDatabase(); //db = helper.getWritableDatabase(); } } } return helper; } public static boolean insertData(ContentValues values){ long index = 0; index = db.insert("person",null,values); values.clear(); if(index >0){ return true; }else { return false; } } /* int index = db.delete("student", "_id= ?", new String[]{""+id}); 按照字段删除,要是多字段可以这样写"_id=3 and sex=女" int index = db.delete("shebei_info", null, null); 全部删除数据 */ public boolean deletDate(int id){ int index = db.delete("student", "_id= ?", new String[]{""+id}); //按照id进行删除数据 //删除后调用更新方法可以使自增id再次从零开始 db.execSQL(" update sqlite_sequence set seq=0 where name='student'"); if(index>0){ return true; } return false; } /* update student set name='haha' where name='hehe'; 更新某一条记录的姓名,where后面是条件语句 */ public void upData(ContentValues values){ db.update("student", values, "id = 3", null); values.clear(); } /* db.rawQuery("select * from student",null); 查询全部数据 db.rawQuery("select * from student where id=3") 按照字段查询 db.raqQuery("select * from student where name like '周%'") 模糊查询,查询name开头包含周的数据 db.raqQuery("select * from student where name like '%周%'") 模糊查询,查询name中包含周的数据 */ public void queryData(){ db.rawQuery("select * from student", null); //查询全部数据 } //向表中增加一列 public void insertColum(){ db.execSQL("alter table student add column sex Integer"); } }