Android-SQLiteOpenHelper

Android-SQLiteOpenHelper

一 概念
是对SOLiteDatabase的封装。主要用于建立和版本号控制,方便我们去建立库表结构

二 用法
又一次封装一个MySqliteOpenHelper类。来实现openOrCreateDatabase类的功能

`public void openOrCreateDatabase()
    { 
        try
        {
                MyDatabaseOpenHelper _myDatabaseOpenHelper = new MyDatabaseOpenHelper(mContext, DATABASE_NAME, null, 2);
            mSqLiteDatabase = _myDatabaseOpenHelper.getWritableDatabase();
        } catch (Exception e)
        {
            // TODO: handle exception
            Log.i("chengzhi log", "table exit");
        }

    }

MySqliteOpenHelper类继承SQLiteOpenHelper重写的方法:
onCreate创建表结构

@Override
    public void onCreate(SQLiteDatabase arg0)
    {
        // TODO Auto-generated method stub
        arg0.execSQL("create TABLE "+TABLE_NAME+"(_id INTEGER PRIMARY KEY AUTOINCREMENT,"+COLUMN_USER_NAME+" VARCHAR(50) NOT NULL, "+COLUMN_USER_ADDRESS+" VARCHAR(50) NOT NULL)");
    }

onUpgrade方法用于创建表和控制表的版本号

@Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2)
    {
        // TODO Auto-generated method stub
        //arg2为新版本号  arg1位旧版本号 
        if (2 == arg2)
        {
            arg0.execSQL("create TABLE Custom (_id INTEGER PRIMARY KEY AUTOINCREMENT,"+COLUMN_USER_NAME+" VARCHAR(50) NOT NULL, "+COLUMN_USER_ADDRESS+" VARCHAR(50) NOT NULL)");
        }
        else if (2 == arg1 && 1 == arg2)
        {
            arg0.execSQL("drop TABLE_NAME");
        }

    }
posted @ 2017-08-08 18:22  lytwajue  阅读(265)  评论(0编辑  收藏  举报