Search code examples
javaandroidsqliteandroid-sqlitecreate-table

Android: what is wrong with my create table statement?


My onCreate method of the SQLiteOpenHelper contains the following code:

Log.d("mytag", "oncreate is called");
db.execSQL("CREATE TABLE TrainingSession (id INTEGER PRIMARY KEY, session_date TEXT, session_status TEXT)");
Log.d("mytag", "tables were created");

The Logcat output contains only the first Log.d:

oncreate is called

And then the app crashes. What is wrong with my create table statement?

EDIT:

Logcat actually says that the table TrainingSession already exists. However, my onUpgrade method looks like this:

Log.d("mytag", "onupgrade is called");
db.execSQL("DROP TABLE IF EXISTS TrainingSet; DROP TABLE IF EXISTS TrainingSession;");
onCreate(db);

and the Logcat output of that method is as expected, the method does get called:

onupgrade is called

If onUpgrade is called and the tables are deleted, then why does onCreate say that TrainingSession already exists?


Solution

  • From https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase#execSQL(java.lang.String)

    execSQL
    added in API level 1
    public void execSQL (String sql)
    Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
    ..............................
    Parameters sql String:
    the SQL statement to be executed.
    Multiple statements separated by semicolons are not supported.

    So execSql() does not support multiple statements separated with ;
    So execute multiple execSql() each for every statement:

    public static final String SQL_DELETE_TABLE1 = "DROP TABLE IF EXISTS TrainingSet"
    db.execSQL(SQL_DELETE_TABLE1); 
    public static final String SQL_DELETE_TABLE2 = "DROP TABLE IF EXISTS TrainingSession"
    db.execSQL(SQL_DELETE_TABLE2);