安卓用于创建数据库提供类SQLiteOpenHelper;由于此类是抽象类,需要创建自定义(此处用MySQLiteOpenHelper)类继承SQLiteOpenHelper后,需要复写oncreate,onUpgrade抽象方法分别用于创建,升级数据库逻辑;SQLiteOpenHelper有非常重要的两个实例方法(getReadableDatabase(),getWritableDatabases()),创建或打开现有数据库(数据库存在则打开,否则创建新数据库)构造函数用于创建数据库的名称,和升级版本
创建一个项目名:databaseTest,
创建自定义(此处用MySQLiteOpenHelper)类
package com.example.databasetest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
/**
* 创建Book表和Category表常量
*/
public static final String CREATE_TABLE_BOOK = "create table Book("
+ "id integer primary key autoincrement," + " author text,"
+ " price real," + " name text,"+" category_id integer)";
public static final String CREATE_TABLE_CATEGORY = "create table Category("
+ "id integer primary key autoincrement," + " type text,"
+ " code text)";
/**
*
* @param context 上下文
* @param name 数据库名
* @param factory 自定义游标
* @param version 版本号
*/
public MySQLiteOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
/**
* 当执行getReadableDatabase(),getWritableDatabase()方法先创建构造函数数据库名后执行初始化创建数据库表
* 注:数据库已存在不再执行
*/
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE_BOOK);
db.execSQL(CREATE_TABLE_CATEGORY);
}
/**
* 升级数据库表
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
switch (oldVersion) {
case 1:
db.execSQL(CREATE_TABLE_CATEGORY);
case 2:
db.execSQL("alter table Book add column category_id integer");
}
}
}
MainActivity.java里代码
package com.example.databasetest;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private MySQLiteOpenHelper helper;
@Override
protected void on