gpt4 book ai didi

java - Android studio SQL找不到表

转载 作者:行者123 更新时间:2023-12-02 02:34:14 30 4
gpt4 key购买 nike

我正在使用SQLiteDatabase我遇到了一个奇怪的问题 - 当我尝试SELECT * FROM时表给了我这个:

no such table: test_table (code 1): , while compiling: SELECT * FROM test_table

但是当我插入同一个表时,没有 Exception已发送。这是我的代码:

从表中获取所有数据的方法:

public List<Test> GetAllTests()
{
List<Test> tests =new ArrayList<Test>();

SQLiteDatabase db = this.getReadableDatabase();

String sql = "SELECT * FROM " + TEST_TABLE;

Cursor cursor = db.rawQuery(sql,null);
if(cursor.moveToFirst())
{
do
{
Test test = new Test();
test.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
test.setSubjectID(cursor.getInt(cursor.getColumnIndex(KEY_SUBJECT_ID)));

String dateString = cursor.getString(cursor.getColumnIndex(KEY_TEST_DATE));
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = null;
try {
date = format.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
test.setDate(date);
test.setGrade(cursor.getDouble(cursor.getColumnIndex(KEY_TEST_GRADE)));

tests.add(test);
}while(cursor.moveToNext());
}
return tests;
}

向同一个表插入数据的方法(无异常):

public long InsertTest(Test test)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SUBJECT_ID,test.getSubjectID());
values.put(KEY_TEST_DATE,test.getDate().toString());
return db.insert(TEST_TABLE,null,values);
}

插入和获取数据的代码:

Test test = new Test(testSubjectID.getSelectedItemPosition(),date);
AddTestToList(test);
try {
dbManager.InsertTest(test);
List<Test> tests = dbManager.GetAllTests();
for (Test test:tests)
{
AddTestToList(test);
}
}catch (Exception e){Log.d("MSG_ERROR",e.toString());}

最佳答案

仅供引用

  • 应用程序卸载不是一个好方法。如果您的应用位于 PLAYSTORE 上,那么?

您应该使用onUpgrade以避免数据丢失

Called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version.

如何?

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.e(TAG, "Updating table from " + oldVersion + " to " + newVersion);


if (oldVersion < 3){ // Here I SET 3. You should use your DB version . When-ever **`adding table`** please increase DB version .
db.execSQL(ALTER_USER_TABLE_1);
db.execSQL(ALTER_USER_TABLE_2);
}

}

更改表

private static final String ALTER_USER_TABLE_1 =  "ALTER TABLE test_table ADD FIELD_NAME TEXT";
private static final String ALTER_USER_TABLE_2 = "ALTER TABLE test_table ADD FIELD_NAME2 TEXT";

关于java - Android studio SQL找不到表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641789/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com