sqlite数据库中SQLiteOpenHelper类的onUpgrade方法

时间:2021-06-16 08:44:58

很多时候我们需要在项目进行中为项目添加一张表,今天终于搞清楚了。

代码如下

package com.zy.dao;

import android.R.integer;
import android.R.string;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper
{
private static final int version = 2;
private static final String DBNAME = "db_fa.db";

public DbHelper(Context context)
{
super(context, DBNAME, null, version);
}

@Override
public void onCreate(SQLiteDatabase db)
{
//创建收入表
db.execSQL("create table if not exists tb_IncomeInfo (income_id integer primary key autoincrement," +
"income_price varchar(10),income_date varchar(20),income_account varchar(10)," +
"income_payer varchar(10),income_category varchar(10),income_remark varchar(100))");

//创建支出表
db.execSQL("create table if not exists tb_ConsumeInfo (consume_id integer primary key autoincrement," +
"consume_price varchar(10),consume_time varchar(20),consume_account varchar(10)," +
"consume_address varchar(20),consume_category varchar(10),consume_remark varchar(100))");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
onCreate(db);
}

}

添加新表后要在onUpgrade执行onCreate方法,并且要把版本号更新(这个很重要!),这里我把版本号改为了。不然是无法添加进去表的!