创建新表时遇到一些问题。当我使用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);
}
}
答案 0 :(得分:34)
这就是应该如何运作的。如果表已存在,CREATE TABLE
将抛出异常。如果表不存在,CREATE TABLE IF NOT EXISTS
将创建表,否则忽略该命令。如果您希望删除旧表,请在DELETE TABLE IF EXISTS
之前使用CREATE TABLE
。如果要更改架构,请使用ALTER TABLE
,而不是CREATE TABLE
。
答案 1 :(得分:-1)
我这样用:
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; }
}