简体   繁体   中英

Adding a column to a table in sql java for android

I was trying to add column to a sql db that I created. this db is for learning purpes so ignore the names of the columns .. I had many problems while trying to do so, but after a LOT of reading I saw few things : 1. I needed to change the DB version so it will start the onUpgrade method 2. I needed to add an "ALTER TABLE" command in my onUpgrade method.

after doing so, the app stopped throwing exceptions, and I thought everything is well. the only thing is that if I try to update the table with the new column it doesn't update anything (even though for some reason it doesn't throw exception).

my main concern is if I should have added the new column commend to the onCreat or no the onUpdate method I created was to add the KEY_KIDS column:

public void onUpgrade(SQLiteDatabase db, int oldVersion,
            int newVersion) throws SQLException{
        Log.w(DBHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", which will destroy all old data");
        db.execSQL("ALTER TABLE " + DATABASE_TABLE[0] +  " ADD COLUMN "
                +  KEY_KIDS + " text not null default kids; ");
        Log.w(DBHelper.class.getName(),
                "Columns added!");
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[0]);
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[1]);
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[2]);
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[3]);
        onCreate(db);
    }

this is the table that I whanted to add a columns to, the new column is KEY_KIDS:

 public static final String Table1= "CREATE TABLE " + DATABASE_TABLE[0] + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_NAME + " TEXT NOT NULL, " + 
                KEY_AGE + " TEXT NOT NULL, " +
                KEY_HOTNESS + " TEXT NOT NULL);" ; //

Should it be like this, or witho the KEY_KIDS declaration (KEY_KIDS + " TEXT NOT..)

pleas help. I have been trying to solve my problem for days and couldn't figure it out. this is the whole code for the sql:

     package com.Dvir.newlearning1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class HotOrNot {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "persons_name";
    public static final String KEY_AGE = "persons_age";
    public static final String KEY_HOTNESS = "persons_hotness";
    public static final String KEY_Hairy = "is_hairy";
    public static final String KEY_KIDS = "has_kids";

    private static final String DATABASE_NAME = "NewDB2";
    private static final String[] DATABASE_TABLE = {"peopleTable", 
            "peopleTable2", "peopleTable3","peopleTable4" };
    private static final int DATABASE_VERSION = 2;

    private DBHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DBHelper extends SQLiteOpenHelper{
        public static final String Table1= "CREATE TABLE " + DATABASE_TABLE[0] + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_NAME + " TEXT NOT NULL, " + 
                KEY_AGE + " TEXT NOT NULL, " +
                KEY_HOTNESS + " TEXT NOT NULL " + 
                KEY_KIDS + " TEXT NOT NULL);" ;
        public static final String Table2 = "CREATE TABLE " + DATABASE_TABLE[1] + " (" +
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    KEY_NAME + " TEXT NOT NULL, " + 
                    KEY_AGE + " TEXT NOT NULL, " +
                    KEY_HOTNESS + " TEXT NOT NULL);";
        public static final String Table3= "CREATE TABLE " + DATABASE_TABLE[2] + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_NAME + " TEXT NOT NULL, " + 
                KEY_AGE + " TEXT NOT NULL, " +
                KEY_HOTNESS + " TEXT NOT NULL);" ;
        public static final String Table4= "CREATE TABLE " + DATABASE_TABLE[3] + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_NAME + " TEXT NOT NULL, " + 
                KEY_AGE + " TEXT NOT NULL, " +
                KEY_HOTNESS + " TEXT NOT NULL);" ;
        public DBHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) throws SQLException{
            // TODO Auto-generated method stub
            db.execSQL(Table1);
            db.execSQL(Table2);
            db.execSQL(Table3);
            db.execSQL(Table4);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,
                int newVersion) throws SQLException{
            Log.w(DBHelper.class.getName(),
                    "Upgrading database from version " + oldVersion + " to "
                            + newVersion + ", which will destroy all old data");
            /*db.execSQL("ALTER TABLE " + DATABASE_TABLE[0] +  " ADD COLUMN "
                    +  KEY_KIDS + " text not null default kids; ");*/
            Log.w(DBHelper.class.getName(),
                    "Columns added!");
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[0]);
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[1]);
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[2]);
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE[3]);
            onCreate(db);
        }

    }

    public HotOrNot(Context c) throws SQLException{
        ourContext = c;
    }
    public HotOrNot open(){
        ourHelper = new DBHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }
    public void close(){
        ourHelper.close();

    }
    public long creatEntry(String name, String age, String hotness, int table, String kids)
        throws SQLException {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME,name);
        cv.put(KEY_AGE, age);
        cv.put(KEY_HOTNESS, hotness);
        cv.put(KEY_KIDS, kids);
        return ourDatabase.insert(DATABASE_TABLE[table], null, cv);
    }
    public long creatEntry(String name, String age, String hotness,String hasKids, int table) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME,name);
        cv.put(KEY_AGE, age);
        cv.put(KEY_HOTNESS, hotness);
        cv.put(KEY_KIDS, hotness);
        return ourDatabase.insert(DATABASE_TABLE[table], null, cv);
    }
    public String getData(int table) {
        // TODO Auto-generated method stub
        String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS, KEY_AGE};
        Cursor c;
        c = ourDatabase.query(DATABASE_TABLE[table], columns, null, null, null, null, null);
        String result = "";
        int iRow = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(KEY_NAME);
        int iAge = c.getColumnIndex(KEY_AGE);
        int iHotness = c.getColumnIndex(KEY_HOTNESS);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            result = result + c.getString(iRow) + " " + c.getString(iName) + " " +
                    c.getString(iAge) + " " + c.getString(iHotness) + "\n";
        }

        return result;
    }
    public String getName(long l) throws SQLException{
        // TODO Auto-generated method stub
        String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS, KEY_AGE};
        Cursor c = ourDatabase.query(DATABASE_TABLE[0], columns, KEY_ROWID + "=" + l, null, null,null, null);
        if (c !=null){
            c.moveToFirst();
            String name = c.getString(1);
            return name;
        }
        return null;
    }
    public String getHotness(long l) throws SQLException{
        // TODO Auto-generated method stub
        String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS, KEY_AGE};
        Cursor c = ourDatabase.query(DATABASE_TABLE[0], columns, KEY_ROWID + "=" + l, null, null,null, null);
        if (c !=null){
            c.moveToFirst();
            int iHot = c.getColumnIndex(KEY_HOTNESS);
            String name = c.getString(iHot);
            return name;
        }
        return null;
    }
    public String getAge(long l)throws SQLException {
        // TODO Auto-generated method stub
        String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS, KEY_AGE};
        Cursor c = ourDatabase.query(DATABASE_TABLE[0], columns, KEY_ROWID + "=" + l, null, null,null, null);
        if (c !=null){
            c.moveToFirst();
            int iAge = c.getColumnIndex(KEY_AGE);
            String name = c.getString(iAge);
            return name;
        }
        return null;
    }
    public void updateEntry(int table, long lRow, String mHotness, String mAge,
            String mName) throws SQLException {
        // TODO Auto-generated method stub
        ContentValues cvUpdate = new ContentValues();
        cvUpdate.put(KEY_NAME, mName);
        cvUpdate.put(KEY_AGE, mAge);
        cvUpdate.put(KEY_HOTNESS, mHotness);
        ourDatabase.update(DATABASE_TABLE[table], cvUpdate, KEY_ROWID + "=" + lRow, null);

    }
    public void deleteEntry(long lRow1) throws SQLException{
        // TODO Auto-generated method stub
        ourDatabase.delete(DATABASE_TABLE[0], KEY_ROWID + "=" + lRow1, null);

    }
}

another thing - I have been trying to creat a multi table DB using a for loop. but, I don't know why, it doesn't let me do it. it tried doing something like: String[] table; for (int i = 0; i<26, i++) { table[i] = "CREATE TABLE " + "DATABASE_TABLE[i]" +... } eclips keeps red flaggin the semicolon in te end of "table" with the error: Syntax error on token ";", { expected after this token does someone know why?

This onUpgrade function does three things:

  1. It adds the kids column;
  2. it drops all tables from the database; and
  3. it calls onCreate , which creates all-new tables.

The purpose of the onUpgrade function is to convert the database from some old version to the new version. Just deleting the old database and then recreating it might be a valid way to do this (if you don't care about the data), but then you would not need to bother with ALTERing things.

Drop steps 2 and 3.

The onCreate function must create a database in the latest version, so it must include all columns of that version.

Look at this part :

public static final String Table1= "CREATE TABLE " + DATABASE_TABLE[0] + " (" +
            KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            KEY_NAME + " TEXT NOT NULL, " + 
            KEY_AGE + " TEXT NOT NULL, " +
            KEY_HOTNESS + " TEXT NOT NULL " + 
            KEY_KIDS + " TEXT NOT NULL);" ;

You forgot the comma ( , ) just before the KEY_KIDS part.

edit the line

db.execSQL("ALTER TABLE " + DATABASE_TABLE[0] +  " ADD COLUMN "
+  KEY_KIDS + " text not null default kids; ");

to

db.execSQL("ALTER TABLE " + DATABASE_TABLE[0] +  " ADD COLUMN "
+  KEY_KIDS + " text not null default 'kids'; ");

notice the single quote 'kids'. if column is of type string (eg: text, varchar, char), put in quotes, unless the data type of type number (eg: integer, decimal) no quotes needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM