4

如何在现有表 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});               
        }       
}

如何添加列 FIRSTNAME(来自 TextView)、LASTNAME(来自 TextView)、DEPARTMENT(来自 Spinner)。

4

2 回答 2

1

如果您只想添加一列或多列,也可以更改现有表。因此,假设您想将名为“my_new_col”的新列添加到名为“my_table”的表中,除了将数据库版本号从 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(...)”中原始表的创建中。

于 2016-07-27T23:14:46.613 回答
0

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

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

static final int DATABASE_VERSION = 2;

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

于 2013-08-01T02:47:25.040 回答