Android的SQLite CREATE TABLE IF NOT EXISTS

创build新表有点问题。 当我使用CREATE TABLE命令时,我的新表格就像它们应该形成的一样,但是当我退出活动时,应用程序崩溃,并且我在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); } } 

Solutions Collecting From Web of "Android的SQLite CREATE TABLE IF NOT EXISTS"

这就是它应该如何工作。 如果表已经存在, CREATE TABLE将会抛出exception。 CREATE TABLE IF NOT EXISTS将创build表,如果它不存在,或者忽略该命令,如果它不存在。 如果您想要删除旧表,请在CREATE TABLE之前使用DELETE TABLE IF EXISTS 。 如果要更改架构,请使用ALTER TABLE ,而不是CREATE TABLE

我这样使用它:

  internal static int checkTable() { DataTable dTable = new DataTable(); try { dbConn = new SQLiteConnection("Data Source=" + dbFileName + ";Version=3;"); dbConn.Open(); sqlCmd.Connection = dbConn; String makeTable = "CREATE TABLE IF NOT EXISTS responde( id INTEGER PRIMARY KEY AUTOINCREMENT, sid TEXT, ans TEXT, answe TEXT, questid TEXT, timestamp TEXT)"; sqlCmd.CommandText = makeTable; sqlCmd.ExecuteNonQuery(); return 1; } catch (SQLiteException) { Console.WriteLine("Error DB 100"); return 0; } catch (IndexOutOfRangeException) { Console.WriteLine("Error DB 101"); return 0; } catch (TypeInitializationException) { Console.WriteLine("Error DB 102"); return 0; } }