-1

I have created a database with a table.I want to add more tables dynamically to that database on the user's command.

The onOpen() method is not useful as it also changes my previous tables that already exist in the database.

  • use rawQuery. You just have to execute a query of "create" in another place that is not onOpen(). https://www.sqlite.org/lang_createtable.html – Ricardo A. Aug 17 '16 at 17:17
  • using Raw query (SQLiteDatabase myDB = null;) -- (myDB = this.openOrCreateDatabase("TheDatabaseName", MODE_PRIVATE, null);) -- (myDB.execSQL("CREATE TABLE IF NOT EXISTS tablename (id INTEGER PRIMARY KEY AUTOINCREMENT, columna TEXT, columnb TEXT);");) -- (myDB.close();) – Tasos Aug 17 '16 at 17:25

1 Answers1

1

I assume you are using SQLite database. If that is the case, a working solution exists here:

Create new table in existing DB in separate SQLiteOpenHelper class.

see rmkrishna's answer from that post, below:

First check the current database version for this database

private final static String DATABASE_NAME = "MainDB";
private static final int DATABASE_VERSION = 1;

public BaseSQLiteOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

and increment the database version(DATABASE_VERSION), and add your new table query in on Upgrade and oncreate method like below.

@Override
public void onCreate(SQLiteDatabase db) {
      db.execSQL("old query no need to change");
      db.execSQL("Create your new table here");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    if (oldVersion < 2) {
       db.execSQL("Create your new table here as well this for update the old DB");
    }
}
Community
  • 1
  • 1
  • Great answer, though instead of an if-statement I would suggest using switch statements to allow for incremental updates. – Waves Aug 17 '16 at 17:23
  • The values of the earlier table are deleted – user3807098 Aug 17 '16 at 18:09
  • Did you increment the version number? Also, you did not provide any code or any Database Version, I see the tags, so I know it is SQLite, but that is all I know, so I am having to do a lot of guessing at this point. You can also check the following link for an alternate answer: http://stackoverflow.com/questions/9804083/how-to-add-second-table-in-database-in-sqlite – Deacon Wolfwood Aug 17 '16 at 19:51