Android SQLite数据库升级 - 代码结构(在onUpgrade中工作但在从那里调用时不工作)

时间:2014-05-16 21:43:09

标签: android database sqlite upgrade alter-table

我正致力于在android中升级sqlite数据库。我认为我已经掌握了这些原则,但我无法理解 - 在我的理解中 - 类似的代码版本。

当我在重写的onUpgrade-procedure(下面的代码1)中直接执行" Alter Table" -Command时,一切都很好。如果我使用完全相同的(sql和java)代码调用一个过程(代码2),数据库不会受到影响。但是,没有错误通知,如果我在使用adb拉动DB-File后在sqlite管理器中运行sql-code,它也能正常工作。

如果有人可以解释"分离版本&#34的问题会很好吗?

注意:要创建数据库,从onCreate ...

调用例程没有问题

"集成"版本,代码1,工作:

public class DBHandler extends SQLiteOpenHelper {
    private static final String DBName = "DynamicValueTracker.db";
    private static final int DBVersion = 2;

    public DBHandler(Context context) {
        super(context, DBName,  null, DBVersion);
        mContext = context;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int OldVersion, int NewVersion) {
        switch (NewVersion) {
            //(deleted further cases for posting question...)
            //This works
            case 2:
                String sqlcmd = "ALTER TABLE countries ADD COLUMN capital TEXT DEFAULT null;";
                db.execSQL(sqlcmd);
            break;
        }
    }
}

"分隔"版本,代码2,不工作:

public class DBHandler extends SQLiteOpenHelper {
    private static final String DBName = "DynamicValueTracker.db";
    private static final int DBVersion = 2;

    public DBHandler(Context context) {
        super(context, DBName,  null, DBVersion);
        mContext = context;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int OldVersion, int NewVersion) {
        switch (NewVersion) {
        //(deleted further cases for posting question...)
            case 2:
                DBUpgrade_V1_to_V2(db);
            break;
        }
    }
}

public void DBUpgrade_V1_to_V2(SQLiteDatabase db) {
    //This is excecuted without throwing errors but does not change the database table 
    String sqlcmd = "ALTER TABLE countries ADD COLUMN capital TEXT DEFAULT null;";
    db.execSQL(sqlcmd);
}

}

0 个答案:

没有答案