你好,游客 登录 注册 搜索
背景:
阅读新闻

SQLiteOpenHelpe创建更新数据库 -

[日期:2013-04-14] 来源:  作者: [字体: ]
public class MainActivity extends Activity implements OnClickListener {
    private static final int INIT_DB_VERSION = 1;
    private static final int UPGRADE_DB_VERSION = 2;
    private Button bt1, bt2;
    private MydbHelper dbh;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1 = (Button) findViewById(R.id.button1);
        bt2 = (Button) findViewById(R.id.button2);
        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.button1:
            dbh = new MydbHelper(getBaseContext(), INIT_DB_VERSION);
            db = dbh.getWritableDatabase();
            Toast.makeText(getBaseContext(), "创建数据库成功", Toast.LENGTH_LONG)
                    .show();
            break;
        case R.id.button2:
            dbh = new MydbHelper(getBaseContext(), UPGRADE_DB_VERSION);
            db = dbh.getWritableDatabase();
            Toast.makeText(getBaseContext(), "更新数据库成功", Toast.LENGTH_LONG)
                    .show();
            break;
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        dbh.close();
    }

}
public class MydbHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "mdb";
    private static final String TAG = "MydbHelper";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        Log.i(TAG, "Begin execute onCreate");
        try {
            db.beginTransaction();
            String sql = "CREATE TABLE TBL_USER(_id INTEGER PRIMARY KEY,name TEXT NOT NULL)";
            db.execSQL(sql);
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
        Log.i(TAG, "Excute onCreate completed");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.i(TAG, "Begin excute onUpgrade");
        try {
            db.beginTransaction();
            String upgradeSql = "ALTER TABLE TBL_USER ADD COLUMN created_dt timestamp NOT NULL DEFAULTE '2010-10-01' COLLATE NOCASE;";
            db.execSQL(upgradeSql);
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
        Log.i(TAG, "Excute onUpgrade completed");
    }
}

 






收藏 推荐 打印 | 录入:admin | 阅读:
相关新闻