一、实现一个类,继承SQLiteOpenHelper类,并实现构造函数,onCreate() onUpgrade()
import android.content.Context; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DbOpenHelper extends SQLiteOpenHelper { private static String name = "mydb.db";// 表示数据库的名称 private static int version = 2;// 表示数据库的版本号码 public DbOpenHelper(Context context) { super(context, name, null, version); } // 当数据库创建的时候,是第一次被执行,完成对数据库的表的创建 @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub //支持的数据类型:整型数据,字符串类型,日期类型,二进制的数据类型, String sql = "create table person(id integer primary key autoincrement,name varchar(64),address varchar(64))"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub String sql = "alter table person add sex varchar(8)"; db.execSQL(sql); } }
只有当调用getWritableDatabase()或getReadableDatabase()时才调用onCreate()
import com.example.android_db.db.DbOpenHelper; import android.test.AndroidTestCase; public class MyTest extends AndroidTestCase { public MyTest() { // TODO Auto-generated constructor stub } public void createDb(){ DbOpenHelper helper = new DbOpenHelper(getContext()); helper.getWritableDatabase(); } }