【发布时间】:2020-11-29 02:50:20
【问题描述】:
因此,我正在尝试设置我的 SQLite 数据库,但我收到了难以纠正的错误。
See the error log here
有一个被抛出的错误的图像,这是我为我的 DatabaseHelper 设置的代码
我的日志中还收到了一些其他错误,我不确定它们与什么有关 - 任何信息都很好 see the logcat output here
错误代码
E/SQLiteLog: (1) table my_manager has no column named
location_description in "INSERT INTO my_manager(location_name,location_county,location_description)
VALUES (?,?,?)"
2020-11-28 19:56:32.986 5665-5665/? E/SQLiteDatabase: Error inserting location_name=Blarney Stone
location_county=Cork location_description=Stone in big wall
android.database.sqlite.SQLiteException: table my_manager has no column named location_description
(code 1 SQLITE_ERROR): , while compiling: INSERT INTO
my_manager(location_name,location_county,location_description) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1045)
a....
这是我的源代码:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "my_manager.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "my_manager";
private static final String COLUMN_ID = "location_id";
private static final String COLUMN_LOCATION = "location_name";
private static final String COLUMN_COUNTY = "location_county";
private static final String COLUMN_DESCRIPTION = "location_description";
public MyDatabaseHelper(@Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_LOCATION + " TEXT, " +
COLUMN_COUNTY + " TEXT, " +
COLUMN_DESCRIPTION + " TEXT );";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addLocation(String location, String county, String description){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_LOCATION, location);
cv.put(COLUMN_COUNTY, county);
cv.put(COLUMN_DESCRIPTION, description);
long result = db.insert(TABLE_NAME, null, cv);
if (result == -1){
Toast.makeText(context, "Failed!" , Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Added Successfully" , Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
}
【问题讨论】:
-
看起来不错 - 您是否有可能添加了描述列但没有增加版本?如果有疑问,请重新安装应用程序或升级版本(假设您可以丢失数据 - 这真的是您在升级中想要的吗?)。
-
谢谢,没有数据会丢失..我如何升级版本/重新安装应用程序?
-
将
DATABASE_VERSION设置为 2 - 这就是触发onUpgrade被调用的原因。重新安装应用程序只是意味着从模拟器或设备上卸载并使用您当前使用的任何方式重新安装。 -
所以我记得我的 Gradel 模块包中的一些代码,然后重新安装了应用程序并冷启动,发挥了魅力,谢谢!您介意解释一下存在的问题,以便我从中学习吗?再次感谢!