在sql java for android中为表添加一列

时间:2014-06-15 08:58:32

标签: java android mysql sql sqlite

我试图将列添加到我创建的sql db中。这个数据库用于学习purpes,所以忽略列的名称.. 在尝试这样做时我遇到了很多问题,但经过大量的阅读后,我看到了一些东西: 1.我需要更改数据库版本,以便启动onUpgrade方法 我需要添加一个" ALTER TABLE"在我的onUpgrade方法中命令。

这样做后,应用程序停止抛出异常,我认为一切都很好。 唯一的问题是,如果我尝试使用新列更新表,它不会更新任何内容(即使由于某种原因它不会引发异常)。

我主要担心的是,我是否应该在onCreat中添加新列表示或不添加 我创建的onUpdate方法是添加KEY_KIDS列:

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);
    }

这是我想要添加列的表,新列是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);" ; //

应该是这样,还是带有KEY_KIDS声明(KEY_KIDS +" TEXT NOT ..)

请求帮助。我已经试图解决我的问题好几天了,无法弄明白。 这是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);

    }
}

另一件事 - 我一直在尝试使用for循环创建一个多表DB。但是,我不知道为什么,它不允许我这样做。它尝试做类似的事情:     String []表;     for(int i = 0; i< 26,i ++){     table [i] =" CREATE TABLE" +" DATABASE_TABLE [i]" + ...     } eclips将红色标记保留在"表格中的分号。有错误:     令牌上的语法错误&#34 ;;",{此标记后的预期 有人知道为什么吗?

3 个答案:

答案 0 :(得分:0)

这个onUpgrade函数做了三件事:

  1. 添加了kids列;
  2. 它从数据库中删除所有表;和
  3. 它调用onCreate,它会创建全新的表。
  4. onUpgrade函数的目的是将数据库从某个旧版本转换为新版本。 只是删除旧数据库然后重新创建它可能是一种有效的方法(如果你不关心数据),但是你不需要为改变事情而烦恼。

    删除第2步和第3步。

    onCreate函数必须在最新版本中创建数据库,因此它必须包含该版本的所有列。

答案 1 :(得分:0)

看看这部分:

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);" ;

您忘记了,部分之前的逗号(KEY_KIDS)。

答案 2 :(得分:0)

编辑

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

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

注意单引号'kids'。如果column的类型为string(例如:text,varchar,char),则放入引号,除非数据类型为number (例如:整数,小数)不需要引号。