BAT job hunting spree | You're out of time balances autumn trick online application, Tencent interview experience

Tencent - alone version of the database how to upgrade and migrate existing data in the past

In the application we have developed, in general, will involve a database, use the data when it will involve upgrading the database, data migration, increased field line and so on. For example, the preservation endpoint will resume information for the user to customize the data saved to the database files involved.

The first version of our application is V1.0, when the iterative version V1.1, we have added a field in the database. So V1.0 database needs to be upgraded in version V1.1, V1.0 version upgrade of the original data in the database can not be lost when the V1.1,

So there should be in place in V1.1 can be detected difference version, and upgrade the database to database software V1.0 V1.1 software can be used. In other words, to increase the field in the database table of V1.0 software, and give the field a default value. How to detect database applications need to upgrade it? There is a method in the class SQLiteOpenHelper

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}

  

When we create an object before if the incoming version number is greater than the version number, which will be called by the judge oldVersion and newVersion can decide how to upgrade the database. The old version of the database table corresponding increase in the fields in this function, and to increase the default value to each record. The new version and the old version will be passed in as a parameter onUpgrade functions for developers to know which databases should be upgraded from version to which version. After the upgrade is completed, the database will automatically store the most recent version number for the current database version number.

Database Upgrade

SQLite provides ALTER TABLE command allows the user to rename or add new fields to an existing table, but you can not delete the field from the table. And can only be added in the end of the table fields, for example, to add a field to the Orders table: "ALTER TABLE Order ADDCOLUMN Country"

code show as below:

public class OrderDBHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "Test.db";
public static final String TABLE_NAME = "Orders";

public OrderDBHelper(Context context, int version) {
    super(context, DB_NAME, null, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
   String sql = "create table if not exists " + TABLE_NAME + " (Id integer primary key, " +
           "CustomName text, OrderPrice integer)";
    db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.e("owen", "DB onUpgrade");
    if (newVersion == 2) {
        db.execSQL("ALTER TABLE " + TABLE_NAME +  " ADD COLUMN Country");
        Cursor cr = db.rawQuery("select * from " + TABLE_NAME, null);
        while (cr.moveToNext()) {
            String name = cr.getString(cr.getColumnIndex("CustomName"));
            ContentValues values = new ContentValues();
            values.put("CustomName", name);
            values.put("Country", "China");
            db.update(TABLE_NAME, values, "CustomName=?", new String[] {name});
        }
        cr.close();
    }
}
OrderDBHelper orderDBHelper = new OrderDBHelper(this, 2);
SQLiteDatabase db = orderDBHelper.getWritableDatabase();

ContentValues contentValues = new ContentValues();
contentValues.put("OrderPrice", 100);
contentValues.put("CustomName", "OwenChan");
db.insert(OrderDBHelper.TABLE_NAME, null, contentValues);


Log.e("owen", "create finish");

Cursor cr = db.rawQuery("select * from " + OrderDBHelper.TABLE_NAME , null);
while (cr.moveToNext()) {
    String name = cr.getString(cr.getColumnIndex("CustomName"));
    Log.e("owen", "name:" + name);
    String country = cr.getString(cr.getColumnIndex("Country"));
    Log.e("owen", "country:" + country);
}
cr.close();
db.close();

  

Database migration

It can be divided into several steps to migrate the database

1, the name of the table into a temporary table

ALTER TABLE Order RENAME TO _Order;

2, create a new table

CREATETABLE Test(Id VARCHAR(32) PRIMARY KEY ,CustomName VARCHAR(32) NOTNULL , Country VARCHAR(16) NOTNULL);

3, import data

INSERTINTO Order SELECT id, “”, Age FROM _Order;

4, delete the temporary table

DROPTABLE _Order;

Through the above four steps, you can complete the old structure of the database migration to a new database structure, and which can also guarantee that the data will not be lost because the upgrade. Of course, if you encounter with reduced field, it can also be achieved by creating a temporary table.

Codes are as follows:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (newVersion == 2) {
        char str = '"';
        db.beginTransaction();
        db.execSQL("ALTER TABLE Order RENAME TO _Order");
        db.execSQL("CREATE TABLE Order(Id integer primary key autoincrement , CustomName VARCHAR(20) NOT NULL,"
                + " Country VARCHAR(32) NOT NULL , OrderPrice VARCHAR(16) NOT NULL)");
        db.execSQL("INSERT INTO Order SELECT Id, " + str + str
                + ", CustomName, OrderPrice FROM _Order");
        db.setTransactionSuccessful();
        db.endTransaction();
    }
}

  

Multiple database version upgrade
if we develop the program has released two versions: V1.0, V2.0, we are developing V3.0. The version number is 1, 2, respectively. In this case, how should we upgrade? The user's choice are:

V1.0 -> V3.0 DB 1 -> 2
V2.0 -> V3.0 DB 2 -> 3

Each database represents a version of the database must be defined, for example, V1.0 database, it may be two tables TableA and TableB, V2.0 if you want to add a table TableC, if you want to modify V3.0 TableC, the database is structured as follows:

V1.0 —> TableA, TableB V1.2 —> TableA, TableB, TableC V1.3 —> TableA, TableB, TableC (Modify)

code show as below:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (1 == oldVersion) {
        String sql = "Create table C....";
        db.execSQL(sql);
        oldVersion = 2;
    }

    if (2 == oldVersion) {
        //modify C
        oldVersion = 3;
    }
}

  

Importing an existing database

/**
 * Created by Owen Chan
 * On 2017-09-26.
 */

public class DbManager {

    public static final String PACKAGE_NAME = "com.example.sql";
    public static final String DB_NAME = "table.db";
    public static final String DB_PATH = "/data/data/" + PACKAGE_NAME;
    private Context mContext;

    public DbManager(Context mContext) {
        this.mContext = mContext;
    }

    public SQLiteDatabase openDataBase() {
        return SQLiteDatabase.openOrCreateDatabase(DB_PATH + "/" + DB_NAME, null);
    }

    public void importDB() {
        File  file = new File(DB_PATH + "/" + DB_NAME);
        if (!file.exists()) {
            try {
                FileOutputStream out = new FileOutputStream(file);
                int buffer = 1024;

                InputStream in = mContext.getResources().openRawResource(R.raw.xxxx);
                byte[] bts = new byte[buffer];
                int lenght;
                while ((lenght = in.read(bts)) > 0) {
                    out.write(bts, 0, bts.length);
                }
                out.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

  

Called

@Override
protected void onResume() {
    super.onResume();
    DbManager dbManager = new DbManager(this);
    dbManager.importDB();
    SQLiteDatabase db = dbManager.openDataBase();
    db.execSQL("do what you want");
}

  

about me

For more information you can click on me  , and very much like to share with everyone, and common progress
 is currently a programmer, Android developers not only to share knowledge, but also to share technical people grew up, including personal summary, experience in the workplace, interviewing experience, you want to make less go a little detour.

Guess you like

Origin www.cnblogs.com/1157760522ch/p/11670679.html