为什么SQLite数据库不会更新?添加列

时间:2012-06-15 17:51:35

标签: android database eclipse sqlite

我已经尝试查看有关此主题的几个已经问过的问题,但我仍然无法让我的文件工作。我想也许一些直接的直接帮助可能正是我所需要的,所以我谦卑地向社区寻求帮助。谢谢你的时间

public class RemindersDbAdapter {

//
// Database Related Constants
//
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "reminders";
private static final int DATABASE_VERSION = 3;

public static final String KEY_TITLE = "title";
public static final String KEY_CUSTOMER = "body";
public static final String KEY_DATE_TIME = "reminder_date_time";
public static final String KEY_END_TIME = "reminder_end_time";
public static final String KEY_ROWID = "_id";


private static final String TAG = "ReminderDbAdapter";
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;

/**
 * Database creation SQL statement
 */
private static final String DATABASE_CREATE =
        "create table " + DATABASE_TABLE + " ("
                + KEY_ROWID + " integer primary key autoincrement, "
                + KEY_TITLE + " text not null, " 
                + KEY_CUSTOMER + " text not null, " 
                + KEY_DATE_TIME + " text not null);" ;



private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper 
{

    DatabaseHelper(Context context) 
    {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        //Adding a Column 
     // If you need to add a column
        if (newVersion > oldVersion) 
        {
            //example I tried pulling from the internet
            db.execSQL(
                "ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
        }

        onCreate(db);
    }
}

1 个答案:

答案 0 :(得分:1)

如果要升级数据库,只需在CREATE语句中添加新列,然后递增版本。

您的代码尝试将列添加到刚刚删除的表中...

db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); // Delete table
...
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0"); // Won't find the table 

只需改变一下:

private static final String DATABASE_CREATE =
        "create table " + DATABASE_TABLE + " ("
                + KEY_ROWID + " integer primary key autoincrement, "
                + KEY_TITLE + " text not null, " 
                + KEY_CUSTOMER + " text not null, " 
                + KEY_DATE_TIME + " text not null, "
                + "new_column INTEGER DEFAULT 0);" ;