本文介绍了为什么使用SQLiteOpenHelper了SQLiteDatabase?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的活动我有例如:

  SQLiteDatabase DB = openOrCreateDatabase(preferences.DB_NAME,Context.MODE_PRIVATE,NULL);
db.execSQL(CREATE TABLE IF NOT EXISTS数据(ID INTEGER PRIMARY KEY,价值VARCHAR));
光标dbResult = db.rawQuery(从数据中选择值,NULL);
//做光标sometning
dbResult.close();
db.close();
 

什么是使用的 SQLiteOpenHelper 喜欢

的好处

  DatabaseHelper帮手=新DatabaseHelper(本);
SQLiteDatabase DB = helper.getWriteableDatabase();
SQLiteDatabase db_2 = helper.getReadableDatabase();
光标dbResult = db_2.rawQuery(从数据中选择值,NULL);
//做光标sometning
dbResult.close();
helper.close();
 

本身类

 公共类DatabaseHelper扩展SQLiteOpenHelper {
    公共DatabaseHelper(上下文的背景下){
        超(背景下,preferences.DB_NAME,空,preferences.DB_VERSION);
    }

    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        查询字符串=CREATE TABLE IF NOT EXISTS数据(ID INTEGER PRIMARY KEY,价值VARCHAR);
        db.execSQL(查询);
        db.close();
    }

    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
    }
}
 

解决方案

SQLiteDatabase

SQLiteOpenHelper

我会说这么多,升级您的应用程序时附带SQLiteOpenHelper的onUpgrade进来非常方便。它主要用于创建和升级/版本管理。 SQLiteDatabase主要是为CRUD操作(你可以创建它,但是这就是SQLiteOpenHelper是)。

In my activity I have for example

SQLiteDatabase db = openOrCreateDatabase(Preferences.DB_NAME, Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY, value VARCHAR)");
Cursor dbResult = db.rawQuery("SELECT value FROM data", null);
// do sometning with cursors
dbResult.close();
db.close();

What's the benefit of using SQLiteOpenHelper like

DatabaseHelper helper = new DatabaseHelper(this);
SQLiteDatabase db = helper.getWriteableDatabase();
SQLiteDatabase db_2 = helper.getReadableDatabase();
Cursor dbResult = db_2.rawQuery("SELECT value FROM data", null);
// do sometning with cursors
dbResult.close();
helper.close();

Class itself

public class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
        super(context, Preferences.DB_NAME, null, Preferences.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY, value VARCHAR)";
        db.execSQL(query);
        db.close();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}
解决方案

SQLiteDatabase

SQLiteOpenHelper

I will say this much, the onUpgrade that comes with SQLiteOpenHelper comes in REALLY handy when upgrading your application. It's mainly for creation and upgrading / version management. SQLiteDatabase is mainly for CRUD operations (you can create with it but that is what SQLiteOpenHelper is for).

这篇关于为什么使用SQLiteOpenHelper了SQLiteDatabase?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 13:38