Romi
Romi

Reputation: 4921

How to add a new table in Sqlite DB

I have created a DB in sqlite and a table in this DB. now i want to add one more table in this table. But am not getting why this new table is not being in DB.

Please suggest.

Upvotes: 2

Views: 12497

Answers (4)

huse
huse

Reputation: 11

To add a new table to database...

step 1: Increase database version

step 2: Create a new table in the method onUpgrade :

@Override

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

  if (newVersion > oldVersion) {  
      db.execSQL("CREATE TABLE NEW_TABLE COLUMN1 TEXT," +
            "COLUMN2 TEXT," +
            "COLUMN3 TEXT");  

 }  
}

Upvotes: 1

Seho Lee
Seho Lee

Reputation: 4108

I guess it sounds like an update problem. If you change your table columns or create new tables you need to update your DB.

SQLiteDatabase YourDatabaseName;
YourDatabaseName = getData.getWritableDatabase();
getData.onUpgrade(YourDatabaseName, 1, 2);

hope this helps

Upvotes: 3

Anthony Graglia
Anthony Graglia

Reputation: 5435

Check out these two links. Sample code is in the second one:

http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

http://code.google.com/p/android-notes/source/browse/trunk/src/com/bitsetters/android/notes/DBHelper.java?r=10

You should use a helper class to access the DB and these links will help. If you do it correctly from the beginning, it will save you a lot of trouble when upgrading later down the road. Hope it helps.

Also, in the second link, the DBHelper.java, you can see the creation strings at the beginning of the file in case you are unaware of what to look for.

private static final String DBVERSION_CREATE = 
  "create table " + TABLE_DBVERSION + " ("
   + "version integer not null);";
private static final String NOTES_CREATE =
  "create table " + TABLE_NOTES + " ("
  + "id integer primary key autoincrement, "
  + "note text, "
  + "lastedit text);";

Upvotes: 0

Tofeeq Ahmad
Tofeeq Ahmad

Reputation: 11975

If you want to create new Table that is not exist then use this.Let you want to create table when btn clicked

        Button btn=new Button(this);
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            SQLiteDatabase db;
            db = databaseclassObject.getWritableDatabase();
            String str="create table tablename(Col1 text not null,col2 text not null);";
            db.execSQL(str);
        }
    });

Upvotes: 1

Related Questions