创建数据库工具类
- SharedPreferences 以XML格式存储数据,存数格式是键值对
- Sqlite Android内置的数据库,一般使用的时候继承 SQLiteOpenHelper,CRUD的常规操作一般写在里面
public class DbHelper extends SQLiteOpenHelper { private static final String DB_NAME = "mydb"; public static final String TB_PERSON = "person"; private static final int VERSION = 1; private static final String CREATE_TABLE_PERSON = "create table person (_id integer primary key autoincrement, name text,age integer)"; private Context mContext; private SQLiteDatabase database; public DbHelper(Context context) { //固定版本号,创建数据库 super(context, DB_NAME, null, VERSION); //获取一个用于操作数据库的SQLiteDatabase实例,有读写的权限 this.database = getWritableDatabase(); this.mContext = context; } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } private void createTable(String str, SQLiteDatabase db) { StringBuffer sqlStr = new StringBuffer(); sqlStr.append(str); db.execSQL(sqlStr.toString()); } public void open() { //存储一个值用于判断表是否已经创建 SharedPreferences prefer = ((Activity)mContext).getSharedPreferences("setting", 0); boolean isCreateTable = prefer.getBoolean("iscreatetable", false); if(!isCreateTable){ //调用创建表的方法 createTable(CREATE_TABLE_PERSON, database); Editor editor = prefer.edit(); editor.putBoolean("iscreatetable", true); editor.commit(); } } public void insert(String tableName, ContentValues cv) { database.insert(tableName, null, cv); } public void delete(String tableName, String id) { StringBuffer sqlStr = new StringBuffer(); sqlStr.append("delete from "); sqlStr.append(tableName); sqlStr.append(" where id=" + id); database.execSQL(sqlStr.toString()); } public void delete(String tableName, String columnName, String columnValue) { StringBuffer sqlStr = new StringBuffer(); sqlStr.append("delete from "); sqlStr.append(tableName); sqlStr.append(" where " + columnName + "=" + columnValue); database.execSQL(sqlStr.toString()); } public void updateById(String tableName, String id, ContentValues cv) { database.update(tableName, cv, "id = ?", new String[] { id }); } public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { return database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); } public void closeDataBase() { database.close(); } public Context getmContext() { return mContext; } }