2 ssummeraw ssummeraw 于 2013.01.09 15:14 提问

SQLite不能打开数据库的异常

在程序的中我从assets中复制了SQLite数据库,可以使用。当把程序第一次安装在仿真器中运行时,获得以下错误。

Failed to open the database. closing it.

android.database.sqlite.SQLiteCantOpenDatabaseException: unable to open database file

E/SQLiteDatabase(7516): at android.database.sqlite.SQLiteDatabase.dbopen(Native Method)
E/SQLiteDatabase(29308):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1013)

E/SQLiteDatabase(29308):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)



E/SQLiteDatabase(29308):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)

E/SQLiteDatabase(29308):    at com.guayama.database.URLDatabaseHelper.checkDBExists(URLDatabaseHelper.java:86)

 E/SQLiteDatabase(29308):   at com.guayama.database.URLDatabaseHelper.createURLDB(URLDatabaseHelper.java:54)

 E/SQLiteDatabase(29308):   at com.guayama.database.URLDatabaseHelper.<init>(URLDatabaseHelper.java:38)

打开数据库用的代码:

SQLiteDatabase.openDatabase(mPath, null,SQLiteDatabase.CREATE_IF_NECESSARY);

也试过以下的代码打开:

checkDB = SQLiteDatabase.openDatabase(mPath, null,
                SQLiteDatabase.OPEN_READONLY);

还有这个代码片段:

 SQLiteDatabase.openDatabase(mPath, null,SQLiteDatabase.NO_LOCALIZED_COLLATORS);

可以帮我看下问题所在吗?谢谢!

2个回答

nana4ever
nana4ever   2013.01.09 15:57
已采纳

我经常用下面的步骤从assets文件夹中复制数据库

private void copyDatabase() throws IOException{

        InputStream inputStream = context.getAssets().open(DB_NAME);
        String dbCreatePath = DB_PATH+DB_NAME;
        OutputStream outputStream = new FileOutputStream(dbCreatePath);
        byte[] buffer = new byte[1024];
        int length;
        while((length = inputStream.read(buffer))>0){
            outputStream.write(buffer,0,length);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
}

然后我会用下面的方法检查一遍:

private boolean checkDatabase(){
    SQLiteDatabase checkDB = null;
    try {
        String dbPath = DB_PATH+DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(dbPath, null,     
            SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLiteException e) {
        // TODO: handle exception
    }
    if(checkDB!=null){
        checkDB.close();}
    return checkDB != null ? true:false;

}
A328240784
A328240784   2013.01.09 16:10

报错说明没有这个文件,你检查一下该文件是否存在吧。file.isExist();

Csdn user default icon
上传中...
上传图片
插入图片