Create an extra table in existing SQLITE (no data loss)

I want to add an additional table to an existing database without data loss. Thus, dropping tables and creating new ones is not an option. What is the best way to do this?

+6
source share
4 answers

This seems to be a lot easier. I am using SQLiteOpenHelper. Therefore, onCreate () is never called if the database already exists. When the version number is incremented, onUpdate () is called. In onUpdate (), I added a new table with "create table if not exists". From the SQLITE.ORG documentation: However, if the β€œIF NOT EXISTING” clause is specified as part of a CREATE TABLE statement and a table or view with the same name already exists, the CREATE TABLE command simply has no effect (and no error message appears). Now the table is created and its fine.

+4
source

the way I did this is to create a separate database, copy everything from the current to a new one, then delete the previous database, and then copy the information from the temp database.

not sure if there is another way to do this, but if there is, I would love to hear about it

+3
source

Create a class that extends SQLiteOpenHelper, override onOpen (SQLiteDatabase db), create a String with the query to create the table, and then use db.execSQL (String str);

0
source

If you want to add a new table to an existing database, then you must do this inside the onUpgrade () method, for example: -

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion == xyz) { db.execSQL(QUERY_CREATE_TABLE_..........NEW); } } 

Here xyz is the old version of the database into which you want to add a new table.

And don't forget to increase DATABASE_VERSION

When we increase the database version, then calling the onUpgrade () method and using the condition add the table.

And also create a new table inside onCreate () with existing tables, for fresh installations like: -

  @Override public void onCreate(SQLiteDatabase db) { db.execSQL(QUERY_CREATE_TABLE_..........OLD); db.execSQL(QUERY_CREATE_TABLE_..........OLD); db.execSQL(QUERY_CREATE_TABLE_..........NEW); } 
0
source

Source: https://habr.com/ru/post/919802/


All Articles