简体   繁体   English

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

[英]How to add column on existing table in android SQLite?

how to add column in the existing table LOGIN.如何在现有表 LOGIN 中添加列。 here's my sample code.这是我的示例代码。

this is my DataBaseAdapter class:这是我的数据库适配器 class:

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

this is my LoginDataBaseAdapter这是我的 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});               
        }       
}

how can I add the columns FIRSTNAME(from TextView), LASTNAME(from TextView), DEPARTMENT(from Spinner).如何添加 FIRSTNAME(来自 TextView)、LASTNAME(来自 TextView)、DEPARTMENT(来自 Spinner)列。

You'll have to update your SQLite database version first of all, then that will run your onUpgrade() method, which will drop all of your data. 首先,您必须更新SQLite数据库版本,然后运行onUpgrade()方法,这将删除所有数据。 Then the table will be remade with the new schema that you have defined in your DATABASE_CREATE string. 然后,将使用您在DATABASE_CREATE字符串中定义的新架构重新生成该表。

So the main issue that this comes with is that you'll have to find a way to recover the data that is already existing in the table as the table will be dropped. 因此,与此相关的主要问题是,您将不得不找到一种方法来恢复表中已存在的数据,因为表将被删除。 You do get to run onUpgrade before this happens though so use this method as a point to save any data you need to from the database. 在发生这种情况之前,您确实可以运行onUpgrade,因此请使用此方法作为从数据库保存所需数据的点。

static final int DATABASE_VERSION = 2;

and update your database creation string. 并更新数据库创建字符串。

You can also alter the existing table if all you want to do is add one or more columns. 如果您只想添加一列或多列,也可以更改现有表。 So say you want to add a new column named 'my_new_col' to a table named 'my_table', in addition to updating your database version number from 1 to 2, you can update the table's schema without losing any data : 因此,假设您要将名为“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 ;
    }
}

That's it. 而已。 Of course you would want to define additional constraints on that new column and you'd want to ensure that the new column is included in the original table's creation in 'onCreate(...)'. 当然,您可能希望在该新列上定义其他约束,并且您希望确保新列包含在'onCreate(...)'中的原始表的创建中。

You have to do three things to successfully adding a column in existing table without losing previous data:您必须做三件事才能在现有表中成功添加列而不丢失以前的数据:

  1. Upgrade your db version: as like:升级您的数据库版本:就像:

     `static final int DB_VERSION = 2;`
  2. Add the new Column in Database creation STATEMENT: as like, here new column is MEMBER_PHOTO :在数据库创建语句中添加新列:就像这里的新列是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. At last in OnUpgrade method add the column in upgraded execute:最后在 OnUpgrade 方法中添加升级执行中的列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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