我已经通过一些sqlite教程并自己编写了这段代码来强化原理。我在几个方面经历的教程各不相同,所以这就是我提出的所有内容的组合。
除了下面列出的两个类之外,我所拥有的只是一个添加,删除,插入,更新和显示数据库数据的活动。
我正在寻求任何反馈。但是我有一些具体的问题。提前谢谢。
助手类
public class BoxScoresHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "boxing_scores.db";
private static final int VERSION = 1;
private static BoxScoresHelper instance = null;
public static BoxScoresHelper getInstance(Context context){
if(instance == null){
instance = new BoxScoresHelper(context);
}
return instance;
}
private BoxScoresHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createBoxerSQLString());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop Table If Exists " + BoxerDAO.TABLE_NAME);
onCreate(db);
}
private String createBoxerSQLString(){
String boxerCreateString = "create table " + BoxerDAO.TABLE_NAME +
"(" + BoxerDAO._ID + " Integer Primary Key AutoIncrement, " +
BoxerDAO.BOXER_NAME + " Text Not Null, " +
BoxerDAO.WEIGHT_CLASS + " Text Not Null, " +
BoxerDAO.WINS + " Integer Not Null, " +
BoxerDAO.LOSSES + " Integer Not Null);";
return boxerCreateString;
}
}
DAO课程
public class BoxerDAO {
public static final String TABLE_NAME = "Boxer";
public static final String _ID = "_id";
public static final String BOXER_NAME = "boxer_name";
public static final String WEIGHT_CLASS = "weight_class";
public static final String WINS = "wins";
public static final String LOSSES ="losses";
private final BoxScoresHelper myScoresHelper;
private SQLiteDatabase myBoxerDB;
public BoxerDAO(Context context){
myScoresHelper = BoxScoresHelper.getInstance(context);
}
public Cursor query(String[] projection,String selection,String[] selectionArgs, String orderBy){
Cursor cursor;
myBoxerDB = myScoresHelper.getReadableDatabase();
cursor = myBoxerDB.query(TABLE_NAME, projection, selection, selectionArgs, null, null, orderBy);
//myBoxerDB.close();
return cursor;
}
public Cursor queryAll(){
Cursor cursor;
myBoxerDB = myScoresHelper.getReadableDatabase();
cursor = myBoxerDB.rawQuery("Select * From " + TABLE_NAME, null);
//myBoxerDB.close();
return cursor;
}
public int delete(int id){
int rowsDel;
myBoxerDB = myScoresHelper.getWritableDatabase();
rowsDel = myBoxerDB.delete(TABLE_NAME, _ID + " = " + id , null);
//myBoxerDB.close();
return rowsDel;
}
public long insert(ContentValues values){
long insertId = -1;
myBoxerDB = myScoresHelper.getWritableDatabase();
insertId = myBoxerDB.insert(TABLE_NAME, null, values);
//myBoxerDB.close();
return insertId;
}
public int update(ContentValues values,String selection, String[] selectionArgs){
int updatedRows;
myBoxerDB = myScoresHelper.getWritableDatabase();
updatedRows = myBoxerDB.update(TABLE_NAME, values, _ID + " = " + selection, selectionArgs);
//myBoxerDB.close();
return updatedRows;
}
}