【发布时间】:2019-09-18 10:23:40
【问题描述】:
我正在尝试通过将列的类型从 String 更改为 Date 类型来迁移数据库。这是我所做的,但没有产生预期的结果......
public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
SimpleDateFormat mDateFormat = new SimpleDateFormat("dd/MM/yyyy");
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
// Create a new table
database.execSQL("CREATE TABLE newExpense (id INTEGER NOT Null, title TEXT, amount TEXT, date INTEGER" +
", PRIMARY KEY(id))");
// Copy the contents of the old table into this new one
database.execSQL("INSERT INTO newExpense (id,title,amount,date) SELECT id,title,amount" +
", 'mDateFormat.parse(date).getTime()' AS date FROM Expense ");
// Delete the old table
database.execSQL("DROP TABLE Expense");
// Rename the new table to the old table
database.execSQL("ALTER TABLE newExpense RENAME TO Expense");
}
};
这是实体之前的样子
// BEFORE (version 1)
@Entity
public class Expense {
@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String amount;
private String date;
...
}
现在
// NOW (version 2)
@Entity
public class Expense {
@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String amount;
private Date date;
...
}
当我在模拟器设备上模拟更新时,结果显示日期错误。我特别不确定迁移中的这种说法
database.execSQL("INSERT INTO newExpense (id,title,amount,date) SELECT id,title,amount" +
", 'mDateFormat.parse(date).getTime()' AS date FROM Expense ")
尤其是'mDateFormat.parse(date).getTime()'。我试图实现的是使用 SimpleDateFormat 解析方法将以前表示为 dd/MM/yyyy 格式的字符串的日期转换为日期对象。这种方法可能有什么问题,或者我怎样才能达到目的?
【问题讨论】:
标签: android sql android-sqlite database-migration android-room