sqlite数据库的助手类不起作用

时间:2014-02-26 20:29:31

标签: android sqlite

我在我的活动中使用了以下代码,它检查数据库错误并且运行正常:

//DB Test
        Boolean databaseError = false;
        SQLiteDatabase myDB = null;
        myDB = this.openOrCreateDatabase("myDB", 0, null);        
        try {
             myDB.rawQuery("SELECT _id FROM occasions;", null);
             myDB.rawQuery("SELECT _id FROM instrumentations;", null); 
             myDB.rawQuery("SELECT _id FROM editions;", null); 
             myDB.rawQuery("SELECT _id FROM composers;", null); 
             myDB.rawQuery("SELECT _id FROM compositions;", null); 
        } catch (SQLiteException e) {
            Log.e("SQLiteException", "SQLiteException");
            databaseError = true;       
        }
        myDB.close();

我想将代码放在以下帮助器类中:

public abstract class BackupHelper {

public static boolean checkDB() {
    Boolean databaseError = false;
    SQLiteDatabase myDB = null;
    myDB = SQLiteDatabase.openDatabase("myDB", null, SQLiteDatabase.OPEN_READWRITE);        
    try {
         myDB.rawQuery("SELECT _id FROM occasions;", null);
         myDB.rawQuery("SELECT _id FROM instrumentations;", null); 
         myDB.rawQuery("SELECT _id FROM editions;", null); 
         myDB.rawQuery("SELECT _id FROM composers;", null); 
         myDB.rawQuery("SELECT _id FROM compositions;", null); 
    } catch (SQLiteException e) {
        Log.e("SQLiteException", "SQLiteException");
        databaseError = true;       
    }
    myDB.close();
    return databaseError;
}

}

但是这会引发以下错误:

  

02-26 21:13:16.397:E / MyTestDatabase(29244):sqlite3_open_v2(“myDB”,& handle,2,NULL)失败   02-26 21:13:17.048:E / AndroidRuntime(29244):引起:android.database.sqlite.SQLiteException:无法打开数据库文件

1 个答案:

答案 0 :(得分:0)

您必须在尝试打开数据库之前创建数据库。

创建一个扩展SQLiteOpenHelper的类

public class DBCreator extends SQLiteOpenHelper {

    // region Properties

    private final static String tag = "DBCreator";

    // endregion

    // region Constructors

    public DBCreator(String name, int version) {
        super(ABApplication.getContext(), name, null, version);
    }

    public DBCreator(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }

    public DBCreator(Context context, String name, CursorFactory factory,
            int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
    }

    // endregion

    // region Overrides
    @Override
    public void onCreate(SQLiteDatabase db) {

        // Execute your CREATE Table script
    }

    // endregion 

}

然后,您可以通过以下方式检索SQLiteDatabase实例:

 SQLiteDatabase SQLiteDatabase = new DBCreator(context, dbName, null, 1) getWritableDatabase();