存储方式三:数据库SQLite(SQLiteOpenHelper)

SQLHelper.java

package com.example.sqlitedemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLHelper extends SQLiteOpenHelper {

	private static final String dbName="mydb.db";
	private static final int version=2;
	
	public SQLHelper(Context context) {
		super(context, dbName, null, version);
	}

	//调用getWritableDatabase()或getReadableDatabase()时,会检查数据库是否存在,若不存在则会调用此方法
	@Override
	public void onCreate(SQLiteDatabase db) {
		System.out.println("onCreate");
		String sql="create table mytable (id integer primary key,name varchar(10) not null)";
		db.execSQL(sql);
		
	}

	//当版本号更新时会调用此方法
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		System.out.println("onUpgrade");
		String sql="drop table if exists mytable";
		db.execSQL(sql);
		onCreate(db);
	}
}

Main.java

package com.example.sqlitedemo;

import android.app.Activity;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;

public class Main extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		SQLiteOpenHelper helper=new SQLHelper(this);
		helper.getWritableDatabase();
	}
}

相关推荐