如何在Android SQLite中的现有表上添加列?

5
如何在现有表LOGIN中添加列。以下是我的示例代码。
这是我的DataBaseAdapter类:
public class DataBaseHelper extends SQLiteOpenHelper
{
    public DataBaseHelper(Context context, String name,CursorFactory factory, int version) 
    {
               super(context, name, factory, version);
    }
    // Called when no database exists in disk and the helper class needs
    // to create a new one.
    @Override
    public void onCreate(SQLiteDatabase _db) 
    {
            _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);

    }
    // Called when there is a database version mismatch meaning that the version
    // of the database on disk needs to be upgraded to the current version.
    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
    {
            // Log the version upgrade.
            Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");


            // Upgrade the existing database to conform to the new version. Multiple
            // previous versions can be handled by comparing _oldVersion and _newVersion
            // values.
            // The simplest case is to drop the old table and create a new one.
            _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
            // Create a new one.
            onCreate(_db);
    }

这是我的LoginDataBaseAdapter。
public class LoginDataBaseAdapter 
{
        static final String DATABASE_NAME = "login.db";
        static final int DATABASE_VERSION = 1;
        public static final int NAME_COLUMN = 1;
        // TODO: Create public field for each column in your table.
        // SQL Statement to create a new database.
        static final String DATABASE_CREATE = "create table "+"LOGIN"+
                                     "( " +"ID"+" integer primary key autoincrement,"+ "USERNAME  text,PASSWORD text); ";
        // Variable to hold the database instance
        public  SQLiteDatabase db;
        // Context of the application using the database.
        private final Context context;
        // Database open/upgrade helper
        private DataBaseHelper dbHelper;
        public  LoginDataBaseAdapter(Context _context) 
        {
            context = _context;
            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        public  LoginDataBaseAdapter open() throws SQLException 
        {
            db = dbHelper.getWritableDatabase();
            return this;
        }
        public void close() 
        {
            db.close();
        }

        public  SQLiteDatabase getDatabaseInstance()
        {
            return db;
        }

        public void insertEntry(String userName,String password)
        {
           ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("USERNAME", userName);
            newValues.put("PASSWORD",password);

            // Insert the row into your table
            db.insert("LOGIN", null, newValues);
            ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
        }
        public int deleteEntry(String UserName)
        {
            //String id=String.valueOf(ID);
            String where="USERNAME=?";
            int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
           // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
            return numberOFEntriesDeleted;
        }   
        public String getSinlgeEntry(String userName1)
        {
            Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName1}, null, null, null);
            if(cursor.getCount()<1) // UserName Not Exist
            {
                cursor.close();
                return "NOT EXIST";
            }
            cursor.moveToFirst();
            String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
            cursor.close();
            return password;                
        }
        public void  updateEntry(String userName,String password)
        {
            // Define the updated row content.
            ContentValues updatedValues = new ContentValues();
            // Assign values for each row.
            updatedValues.put("USERNAME", userName);
            updatedValues.put("PASSWORD",password);

            String where="USERNAME = ?";
            db.update("LOGIN",updatedValues, where, new String[]{userName});               
        }       
}

我该如何添加来自TextView的FIRSTNAME、LASTNAME和来自Spinner的DEPARTMENT列?
3个回答

1
如果您只想添加一个或多个列,也可以更改现有表格。因此,假设您想要向名为“my_table”的表中添加一个名为“my_new_col”的新列,并将数据库版本号从1更新为2,则可以在不丢失任何数据的情况下更新表模式。
...
@Override
public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) {
    switch( newVersion ) {

        case 2: /* this is your new version number */

            // ... Add new column 'my_new_col' to table 'my_table'
            db.execSQL( "alter table my_table add column my_new_col" ) ;
            break ;
    }
}

那就这样了。当然,您可能希望对新列定义其他约束,并确保在“onCreate(...)”中包含新列的创建。

我会失去之前的数据。这样正确吗? - Noor Hossain
不,你不会的。只要你的列定义有效,它就会为所有现有记录添加该列。换句话说,定义列默认值是一个好主意。 - El Stepherino

0

在现有表格中成功添加列且不丢失先前数据,您需要完成三件事:

  1. 升级您的数据库版本,例如:

    `static final int DB_VERSION = 2;`
    
  2. 在数据库创建语句中添加新列,例如,这里的新列是 MEMBER_PHOTO

    private static final String CREATE_TABLE = "create table "+ TABLE_MEMBER + "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+ MEMBER_NAME + " TEXT NOT NULL, " + MEMBER_PHOTO + " TEXT NOT NULL);";

  3. 最后,在 OnUpgrade 方法中将该列添加到升级执行中:

      @Override
         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
             // TODO Auto-generated method stub
    
             // 新版本 2:
    
             String sql = "ALTER TABLE " + TABLE_MEMBER + " ADD COLUMN " +
                     "MEMBER_PHOTO" + " TEXT NOT NULL DEFAULT '' ";
             db.execSQL(sql);
    
         }
    

0

首先,您需要更新您的SQLite数据库版本,然后它将运行您的onUpgrade()方法,该方法将删除所有数据。然后,使用您在DATABASE_CREATE字符串中定义的新模式重新创建表格。

因此,这个主要问题是您必须找到一种方法来恢复已经存在于表格中的数据,因为表格将被删除。不过,在此发生之前,您可以运行onUpgrade方法,因此请使用此方法保存您需要从数据库中保存的任何数据。

static final int DATABASE_VERSION = 2;

并更新您的数据库创建字符串。


你的意思是我将把 static final int DATABASE_VERSION = 1; 改为 static final int DATABASE_VERSION = 2; 然后再像这样添加列... static final String DATABASE_CREATE = "create table "+"LOGIN"+ "( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text, FIRSTNAME text, LASTNAME text, DEPARTMENT text); "; 是这样吗? - Karl Caday
是的,但只有在您可以接受表中数据丢失的情况下才这样做。 - Paul Thompson
是的,但它不会更新。相反,我需要更改整个表格-.- - Karl Caday
当您更改DATABASE_VERSION时,它不会升级吗?只要调用构造函数,它就应该升级。如果您想更改整个表格,那也很容易,您只需要更改创建表格脚本即可。 - Paul Thompson
只是一个提示...您可能需要卸载应用程序并重新安装它。清除应用程序数据只会清空数据库,而不会删除它。数据库升级可能已经在更新的第一次安装时发生,您将不会再看到它被调用。 - javahead76
这就是为什么你要更改数据库版本。如果你继续递增它,那么它将始终调用数据库升级。 - Paul Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接