您的位置:首页 > 移动开发 > Android开发

android中sqlite数据库升级方案

2013-12-03 08:39 387 查看
android开发中,如果大家使用到了sqlite就会牵涉到它的升级问题,因为升级后的表结构可能完全不一样,会有字段的添加或者删除等。。

sqlite升级思路:

1:将表A重新命名:例如重新命名为:temp_A

2:创建新标A

3: 将temp_A中的数据【也就是更新前的数据】插入到新表A

我的案例分两种:1:一张表字段发生变化 2: 数据库中添加新的表

先看1:一张表字段发生变化

直接代码走起:

SQLiteOpenHelper类:

package com.example.sqldbupdatedemo;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.database.sqlite.SQLiteOpenHelper;

import android.util.Log;

/****

*

* @author jone

*

* 2013-12-2

* com.example.sqldbupdatedemo

*

*/

public class MySqlHelper extends SQLiteOpenHelper

{

//DB name

public static final String DB_NAME = "TestUp.db";

//初始的版本号

public static final int DB_VERSION = 1;

//表名称

public static String tname = "myup";

//创建表的sql语句

public static final String CREATE_TASK_TB = "create table if not exists " + tname + "(name text,pwd text)";

public MySqlHelper(Context context, String name, int version)

{

super( context, name, null, version );

// TODO Auto-generated constructor stub

}

@Override

public void onCreate(SQLiteDatabase db)

{

// TODO Auto-generated method stub

db.execSQL( CREATE_TASK_TB );

Log.i( "tag", "oncreat db" );

}

@Override

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

{

Log.i( "tag", " onUpgrade db" );

//获取到旧表中的字段【也就是新表中保留的字段】

String columns = getColumnNames( db, tname );

//升级

updateTable( db, tname, columns );

}

private void updateTable(SQLiteDatabase db, String tableName, String columns)

{

try

{

db.beginTransaction();

String reColumn = columns.substring( 0, columns.length() - 1 );

// rename the table

String tempTable = tableName + "texp_temptable";

String sql = "alter table " + tableName + " rename to " + tempTable;

db.execSQL( sql );

// drop the oldtable

String dropString = "drop table if exists " + tableName;

db.execSQL( dropString );

// creat table

String ss = "create table if not exists " + tableName + "(name text,pwd text,rpwd text)";

db.execSQL( ss );

// load data

String newStr = "rpwd";

String newreColumn = reColumn + "," + newStr;

String ins = "insert into " + tableName + " (" + newreColumn + ") " + "select " + reColumn + "" + " " + " from "

+ tempTable;

db.equals( ins );

db.setTransactionSuccessful();

}

catch (Exception e)

{

// TODO: handle exception

Log.i( "tag", e.getMessage() );

}

finally

{

db.endTransaction();

}

}

// 获取升级前表中的字段

protected String getColumnNames(SQLiteDatabase db, String tableName)

{

StringBuffer sb = null;

Cursor c = null;

try

{

c = db.rawQuery( "PRAGMA table_info(" + tableName + ")", null );

if (null != c)

{

int columnIndex = c.getColumnIndex( "name" );

if (-1 == columnIndex)

{

return null;

}

int index = 0;

sb = new StringBuffer( c.getCount() );

for ( c.moveToFirst(); !c.isAfterLast(); c.moveToNext() )

{

sb.append( c.getString( columnIndex ) );

sb.append( "," );

index++;

}

}

}

catch (Exception e)

{

e.printStackTrace();

}

finally

{

if (c != null)

{

c.close();

}

}

return sb.toString();

}

}

具体的使用者Activity

package com.example.sqldbupdatedemo;

import java.util.ArrayList;

import android.app.Activity;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener

{

MySqlHelper dbHelper;

SQLiteDatabase db;

TextView tView1;

TextView tView2;

TextView tView3;

Button button;

Entity entity1;

Entity entity2;

ArrayList<Entity> list;

@Override

protected void onCreate(Bundle savedInstanceState)

{

super.onCreate( savedInstanceState );

setContentView( R.layout.activity_main );

dbHelper = new MySqlHelper( this, MySqlHelper.DB_NAME, 7 );

list = new ArrayList<MainActivity.Entity>();

initView();

initSql();

}

private void showInfo()

{

db = dbHelper.getReadableDatabase();

Cursor cursor = null;

try

{

cursor = db.rawQuery( "select * from myup", null );

while (cursor.moveToNext())

{

String name = cursor.getString( cursor.getColumnIndex( "name" ) );

String pwd = cursor.getString( cursor.getColumnIndex( "pwd" ) );

String rpwd = cursor.getString( cursor.getColumnIndex( "rpwd" ) );

// String myl = cursor.getString( cursor.getColumnIndex( "myl" ) );

Entity entity = new Entity( name, pwd, rpwd );

list.add( entity );

}

}

catch (Exception e)

{

// TODO: handle exception

e.printStackTrace();

Log.i( "tag", e.getMessage() );

}

if (cursor != null)

{

cursor.close();

db.close();

}

entity1 = list.get( 0 );

entity2 = list.get( 1 );

tView1.setText( entity1.getName() + "---" + entity1.getPwd() + "--" + entity1.getRpwd() );

tView2.setText( entity2.getName() + "---" + entity2.getPwd() + "--" + entity2.getRpwd() );

}

private void initView()

{

tView1 = (TextView) findViewById( R.id.en1 );

tView2 = (TextView) findViewById( R.id.en2 );

tView3 = (TextView) findViewById( R.id.en3 );

button = (Button) findViewById( R.id.btn );

button.setOnClickListener( this );

}

private void initSql()

{

db = dbHelper.getWritableDatabase();

String insert1 = "insert into myup(name,pwd) values(?,?)";

db.execSQL( insert1, new String[] { "zhangsan", "123456" } );

String insert2 = "insert into myup(name,pwd) values(?,?)";

db.execSQL( insert2, new String[] { "lisi", "789654" } );

db.close();

}

class Entity

{

String name;

String pwd;

String rpwd;

public Entity(String name, String pwd, String rwpd)

{

this.name = name;

this.pwd = pwd;

this.rpwd = rpwd;

}

public String getName()

{

return name;

}

public void setName(String name)

{

this.name = name;

}

public String getPwd()

{

return pwd;

}

public void setPwd(String pwd)

{

this.pwd = pwd;

}

public String getRpwd()

{

return rpwd;

}

public void setRpwd(String rpwd)

{

this.rpwd = rpwd;

}

}

@Override

public void onClick(View v)

{

switch (v.getId())

{

case R.id.btn:

showInfo();

break;

default:

break;

}

}

}

注释比较详细了

接下来是第二中情况:2 数据库中添加新的表

数据库升级的逻辑定义。。这点其实是数据库升级最重要的部分,我们在升级之前要定义好相应的升级逻辑,当我们在创建SQLiteOpenHelper类会传入不同的版本号,此刻我们更具这个version来做升级逻辑。。

例如我们的app已经有了两个版本V1.0,V1.2,现在我们在开发V1.3,那么我们对应的数据库版本号依次为18,19,20

对于这种情况,我们应该如何实现升级?

用户的选择有:

1) V1.0 -> V1.3 DB 18 -> 20

2) V1.1 -> V1.3 DB 19 -> 20

注意: 数据库每一个版本所代表的数据库必须是定义好的,比如说:V18数据库有两张表T1,T2,如果V19要添加一张表T3,V20要修改T3中的某些字段则逻辑是这样子的:

V18--> T1,T2

V19-->T1,T2,T3

V20-->T1,T2,T3(更新)

在onUpgrade()方法的实现如下:

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

{

int upgradeVersion = oldVersion;

if (18 == upgradeVersion) {

// Create table T3

String sql = "CREATE TABLE ...";

db.execSQL(sql);

upgradeVersion = 1

}

if (20 == upgradeVersion) {

// Modify table T3

upgradeVersion = 20;

}

if (upgradeVersion != newVersion) {

// Drop tables

db.execSQL("DROP TABLE IF EXISTS " + tableName);

// Create tables

onCreate(db);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: