sqlite android 本地数据库,用来存储少量的数据 或者 用来处理 缓存
public class SqliteDbHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static SqliteDbHelper instance;
private static String TABLE_NAME;
private Map CREATE_TABLE_SQL = new HashMap<>();
//SQLiteOpenHelper创建数据库时默认是将数据库保存在’/data/data/应用程序名/databases’目录下
protected static SqliteDbHelper getInstance(Context context) {
if (null == instance) {
TABLE_NAME = context.getResources().getString(R.string.app_name) + ".db";
instance = new SqliteDbHelper(context, TABLE_NAME);
}
return instance;
}
private SqliteDbHelper(Context context, String name) {
super(context, name, null, DB_VERSION, null);
CREATE_TABLE_SQL.clear();
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
for (String sql : CREATE_TABLE_SQL.values()) {
sqLiteDatabase.execSQL(sql);
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
public boolean createTable(String name, String... items) {
if (CREATE_TABLE_SQL.containsKey(name)) {
return false;
}
String sql = "create table if not exists " + name
+ " (Id integer primary key";
for (String item : items) {
sql += (", " + item + "text");
}
sql += ")";
CREATE_TABLE_SQL.put(name, sql);
this.onCreate(this.getReadableDatabase());
return true;
}
}
需要一个 manager 来管理所有的 增删改查 同时需要自己 写简单 sql 语句
public class SqliteManager {
private static SqliteManagerinstance;
private static SqliteDbHelperdbHelper;
private void SqliteManager(){}
public static SqliteManager getInstance(Context context){
if (null ==instance){
instance =new SqliteManager();
dbHelper = SqliteDbHelper.getInstance(context);
}
return instance;
}
public void createTable(String name, String... items){
dbHelper.createTable(name, items);
}
//遍历出表名
public String getAllTableName(Context context) {
SqliteDbHelper helper = SqliteDbHelper.getInstance(context);
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
String result =null;
Cursor cursor = db.rawQuery("select name from sqlite_master where type='table';",null);
Log.e("xiaobo cursor column ", cursor.getCount()+"");
while(cursor.moveToNext()){
//遍历出表名
result += cursor.getString(0) +" ";
}
db.setTransactionSuccessful();
db.endTransaction();
return result;
}
public int insertTableItem(Context context, String name, ContentValues item) {
SqliteDbHelper helper = SqliteDbHelper.getInstance(context);
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
db.insertOrThrow(name,null, item);
db.setTransactionSuccessful();
db.endTransaction();
return 0;
}
}
只有增加的 方法,个人目前 喜欢写 简单的sql 语句进行查询。但是依旧需要 model类的引入。
网友评论