Question

I have table called person with 3 columns .They are ID,NAME and PASSWORD .I need to add new column called AGE.I try it this way but it doesn't work for me please help me to overcome this problem

public class Userdb {
    public static final String KEY_ROWID = "Id";
    public static final String KEY_NAME = "Person_name";
    public static final String KEY_PASSWORD = "Person_password";
    public static final String KEY_AGE = "Person_age";

    private static final String DATABASE_NAME = "People_db_1";
    private static final String DATABASE_TABLE = "people_table";
    private static final int DATABASE_VERSION = 1;


    private static class Dbhelper extends SQLiteOpenHelper {

        public Dbhelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub

            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
                    + " TEXT NOT NULL, " + KEY_PASSWORD + " TEXT NOT NULL); ");

        }


        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

            db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
            db.execSQL("ALTER TABLE " + DATABASE_TABLE +" ADD COLUMN "+ KEY_AGE +" TEXT NOT NULL ; ");
            onCreate(db);

        }

    }
Était-ce utile?

La solution

Database Upgrading

The constructor of your implementation of SQLiteOpenHelper should call the super constructor, passing along the database name and version. The onUpgrade() method will only be called when the version integer is larger than the current version running in the emulator. If you want the onUpgrade() method to be called, you need to increment the version number in your code.

See More about onCreate() and onUpgrade()

Autres conseils

I don't think there is ALTER COLUMN in sqlite.

Just follow the steps as suggested in this link

Let me know if it's helped.

A newly added column contains NULL values (or whatever value you specified in the DEFAULT clause), so you cannot add a column with a NOT NULL constraint. Furthermore, you cannot add a column to a table that does not exist (because you have just dropped it).

You can either

  • remove the NOT NULL constraint or add a DEFAULT clause (and don't drop the table); or
  • drop the old table and create the new table with the complete CREATE TABLE statement.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top