gpt4 book ai didi

如果不存在则创建表

转载 作者:IT王子 更新时间:2023-10-29 06:18:39 27 4
gpt4 key购买 nike

创建新表时遇到一点问题。当我使用 CREATE TABLE 命令时,我的新表按原样形成,但是当我退出 Activity 时,应用程序崩溃并且我在 logcat 中得到一个 TABLE ALREADY EXISTS。如果我使用 CREATE TABLE IF NOT EXISTS,则不会形成新表,而只是将我的新数据行添加到以前的表中,它不会崩溃。这有什么问题?我想添加表而不给我已经存在的表,我希望它添加而不将行添加到不同的表。

SqliteHelper 类:

public class MySQLiteHelper extends SQLiteOpenHelper {


public static final String TABLE_NAME = MainActivity.NameName;

public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
public static final String COLUMN_LAT = "lat";
public static final String COLUMN_LONG = "long";
public static final String COLUMN_RADI = "radi";
private static final String DATABASE_NAME = "spraylogs.db";
private static final int DATABASE_VERSION = 1;



public static final String NEWTABLE = "CREATE TABLE "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null," + COLUMN_LAT+ "," + COLUMN_LONG + "," + COLUMN_RADI + ");";

public static final String SaveIt = "CREATE TABLE IF NOT EXISTS "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null," + COLUMN_LAT+ "," + COLUMN_LONG + "," + COLUMN_RADI + ");";



MySQLiteHelper(Context context) {
super(context, context.getExternalFilesDir(null).getAbsolutePath() + "/" + DATABASE_NAME, null, DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase database) {
}

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

onCreate(db);
}

}

最佳答案

它应该是这样工作的。如果表已经存在,CREATE TABLE 将抛出异常。如果表不存在,CREATE TABLE IF NOT EXISTS 将创建表,如果存在则忽略该命令。如果您希望它删除旧表,请在 CREATE TABLE 之前使用 DELETE TABLE IF EXISTS。如果要更改架构,请使用 ALTER TABLE,而不是 CREATE TABLE

关于如果不存在则创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21838205/

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