大家好,我正在创建游戏,我是 sql lite 的新手。我有一个用于插入数据库的代码,但我不知道如何将其最大化为 10,而且我也不知道如何将玩家的新分数与旧分数进行比较。另外,如果新分数击败前 10 名中的 1 名,我如何删除前 10 名中得分最低的。我正在寻找具有良好解释的出色代码,以便我了解代码流程。
这是我的数据库类:
public class highscore {
private static final String DATABASE_NAME = "topscoredb";
private static final String DATABASE_TABLE = "tablescore";
private static final int DATABASE_VERSION = 2;
public static final String KEY_ROWID = "_id";
public static final String KEY_SCORE = "score";
public static final String KEY_NAME = "players_name";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_SCORE + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXIST" + DATABASE_TABLE);
onCreate(db);
}
}
public highscore(Context c){
ourContext = c;
}
public highscore open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String tscore) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_SCORE, tscore);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_SCORE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,null, null);
String result = "";
int irow = c.getColumnIndex(KEY_ROWID);
int iname = c.getColumnIndex(KEY_NAME);
int iscore = c.getColumnIndex(KEY_SCORE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(irow)+ " " +c.getString(iname)+" "+
c.getString(iscore) + "\n";
}
return result;
}
}
我应该使用方法吗?