gpt4 book ai didi

android - android 中的 SQLite 数据库中有多个表?

转载 作者:行者123 更新时间:2023-11-30 04:42:39 25 4
gpt4 key购买 nike

我在 android 的 sqlite 数据库中创建多个表时遇到问题。这是我的代码

   public class DataHelper {
private static final String DATABASE_NAME = "example.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "table1";
private static final String SETTING_TABLE="setting";

private Context context;
private SQLiteDatabase db;

private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME +
"(name) values (?)";
private static final String INSERTSETTING = "insert into " + SETTING_TABLE +
"(name) values (?)";

public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
this.insertStmt = this.db.compileStatement(INSERTSETTING);
}

public SQLiteDatabase getDb() {
return this.db;
}

public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME +
" (id INTEGER PRIMARY KEY, name TEXT)");
db.execSQL("CREATE TABLE " + SETTING_TABLE +
" (id INTEGER PRIMARY KEY, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}

最佳答案

增加DATABASE_VERSION的值,否则不会调用onUpgrade。

我注意到您没有在 onUpgade 中删除 SETTING_TABLE,并且在将 INSERT 替换为 INSERTSETTING 时丢失了代码顶部的第一个插入语句。

关于android - android 中的 SQLite 数据库中有多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5669156/

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