2014-02-17 101 views
8

在创建新表时遇到一些问题。当我使用CREATE TABLE命令时,我的新表格按其应有的形式形成,但是当我退出该活动时,应用程序崩溃并在logcat中获得TABLE ALREADY EXISTS。如果我使用CREATE TABLE IF NOT EXISTS,则不会形成新表,但会将我的新数据行添加到上一个表中,并且不会崩溃。这有什么问题?我想添加没有它给我已经存在的表,我希望它添加没有它添加行到不同的表。android sqlite创建表如果不存在

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); 
} 

} 

回答

28

这就是它的应该如何工作。如果表已经存在,CREATE TABLE将引发异常。如果该表不存在,或者忽略该命令(如果存在),则CREATE TABLE IF NOT EXISTS将创建表。如果您想要删除旧表,请在CREATE TABLE之前使用DELETE TABLE IF EXISTS。如果要更改架构,请使用ALTER TABLE而不是CREATE TABLE

+0

我不明白,为什么在CREATE TABLE IF NOT EXISTS是添加行前面的表。 – johnsonjp34

+0

它不会,但如果您有任何添加行的代码,则会将其添加到该现有表中 - CREATE IF NOT EXISTS不会删除旧数据。 –

-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; } 
    }