5

我创建了一个静态方法来访问我的一个活动中的数据库,但我在打开数据库时不断出错。

主要活动

 public static String getStudentData() {

    SQLiteDatabase sampleDB =  null;

    try {
            //NOT WORKING
        sampleDB =  SQLiteDatabase.openDatabase("studentDB",null, SQLiteDatabase.CREATE_IF_NECESSARY); 
            //Also not working
        //sampleDB =  SQLiteDatabase.openOrCreateDatabase("studentDB", null);

        Cursor c = sampleDB.rawQuery("SELECT * FROM student where id='1'", null);

        if (c != null ) {
            if  (c.moveToFirst()) {
                do {
                    //...                       
                }while (c.moveToNext());
            } 
        }
        c.close();
    } catch (Exception se ) {
    } finally {
            sampleDB.close();
    }
}

其他活动

String student = MainActivity.getStudentData();

我已经得到sqlite3_open_v2("studentDB", &handle, 6, NULL) failed. 找不到问题所在...我也尝试过使用MODE_WORLD_WRITEABLE. 目前MODE_PRIVATE用于创建数据库。请帮帮我!

4

2 回答 2

6

第一个参数openDatabase应该是 db 的完整路径,因此如果:

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";

private static String DB_NAME = "studentDB";

那么你应该打电话:

sampleDB =  SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY); 
于 2011-10-12T19:29:25.693 回答
3

使用方法ContextWrapper#getDatabasePath(java.lang.String)并将结果传递给SQLiteDatabase.openDatabase

File dbFile= myActivity.getDatabasePath("studentDB");
sampleDB = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY);
于 2012-04-27T11:44:27.983 回答