如何在Android应用程序中刷新DataBase

时间:2014-03-23 10:07:13

标签: android sqlite

我的应用中有一个数据库。在以前的版本中,它只包括"得分"柱。 在新版本中,我想添加2个新的colunms - " level"和"难度"。

如何在不造成任何错误的情况下刷新它?

数据库类的代码:

public class ScoreDataBase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "score_database.db";
private static final int DATABASE_VERSION = 1;

public static final String UID = "_id";
public static final String SCORE = "score";
public static final String DIFF = "difficulty";
public static final String LEVEL = "level";

static final String TABLE_NAME = "score_table";

private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
        + TABLE_NAME + " (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + SCORE + " INT "+DIFF +" INT "+ LEVEL + " INT);";

private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS "
        + TABLE_NAME;

public ScoreDataBase(Context context) {
    // TODO Auto-generated constructor stub
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(SQL_CREATE_ENTRIES);
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL(SQL_DELETE_ENTRIES);
    onCreate(db);
}

}

在我的应用程序中,我按照以下方式获取数据:

sqh = new ScoreDataBase(this);
    sqdb = sqh.getWritableDatabase();
    best_score = 0;
    String query = "SELECT " + ScoreDataBase.SCORE + 
            " FROM " + ScoreDataBase.TABLE_NAME +
            " ORDER BY " + ScoreDataBase.SCORE + " DESC LIMIT 1";

    Cursor cursor2 = sqdb.rawQuery(query, null);
    while (cursor2.moveToNext()) {
        best_score = cursor2.getInt(cursor2
                .getColumnIndex(ScoreDataBase.SCORE));
        //Log.i("LOG_TAG", "ROW " + id + " HAS NAME " + name);
    }
    cursor2.close();

它有效。但是,如果我将查询更改为:

String query = "SELECT " + ScoreDataBase.SCORE + 
            " FROM " + ScoreDataBase.TABLE_NAME +
            " WHERE " +ScoreDataBase.DIFF+" = "+ String.valueOf(diff)+
            " AND " +ScoreDataBase.LEVEL+" = "+ String.valueOf(lev_num)+
            " ORDER BY " + ScoreDataBase.SCORE + " DESC LIMIT 1";

停止工作!该怎么办?如何刷新DataBase?

感谢所有答案!

1 个答案:

答案 0 :(得分:1)

首先,您的CREATE TABLE

存在语法问题
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
    + TABLE_NAME + " (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
    + SCORE + " INT "+DIFF +" INT "+ LEVEL + " INT);";

在列规范之间添加逗号:

private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
    + TABLE_NAME + " (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
    + SCORE + " INT, "+DIFF +" INT, "+ LEVEL + " INT);";

然后,要使CREATE TABLE运行,请增加数据库版本或只卸载您的应用。见When is SQLiteOpenHelper onCreate() / onUpgrade() run?