創建數據庫工具類
- 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;
}
}
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

