Android下创建SQLite数据库的正确姿势
2.1 核心类
① SQLiteOpenHelper
② SQLiteDataBase
2.2 使用方法
第一步: 创建一个类继承 SQLiteOpenHelper 并实现父类的构造
public class MySQLOpenHelper extends SQLiteOpenHelper { public MySQLOpenHelper(Context context) { /**第一个参数 上下文 第二个参数 创建的数据库文件名字 第三个参数 游标工厂 通过游标工厂可以获得执行查询语句的返回值 Curor 可以传 null 采用默认的游标工厂 第四个参数 数据库的版本号 从1开始 **/
super(context, "itheima.db", null, 1);
第二步 从写onCreate 方法 和onUpgrade 方法
第三步 在Activity中 创建MySQLOpenHelper对象( 注意 !!!! 至此并没有创建数据库)
第四部 调用 MySQLOpenHelper的getReadableDatabase或getWriteableDatabase方法获取SQLiteDataBase对象
public class MainActivity extends Activity { private SQLiteDatabase db; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLOpenHelper openHelper = new MySQLOpenHelper(this); //获取SQLiteDatabase对象 如果数据库不存在则创建 如果存在则打开 如果磁盘空间满则出错 db = openHelper.getWritableDatabase(); //与getWritableDatabase功能类似 但如果磁盘空间满则会返回一个只读的数据库 db = openHelper.getReadableDatabase(); }