Android:打开db文件时出错

时间:2012-09-07 09:16:02

标签: android database sqlite

我正在使用此代码检查数据库是否已存在:

public static boolean checkDataBase(String DB_FULL_PATH) {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (SQLiteException e) {
        // database doesn't exist yet.
    }
    return checkDB != null ? true : false;
}

我的助手课程是:

public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "my_db";
    private static final String TABLE_NAME = "products";
    private static final String KEY_NAME = "pname";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + KEY_NAME + " TEXT" + ")";
        db.execSQL(CREATE_PRODUCTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public void addProducts(String product_name) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, product_name); // Product Name
        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public String getProducts() {

        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(selectQuery, null);
        String s = "default";
        if (cursor.moveToFirst()) {
            int n = cursor.getCount();
            s = cursor.getString(0);
        }
        cursor.close();
        return s;
    }
}

当我尝试这个时:

checkDataBase(Environment.getDataDirectory() + "/data/com.android.my_app/databases/my_db.db")

我在log cat中收到此错误消息:

sqlite returned: error code = 14, msg = cannot open file at source line 25467

sqlite3_open_v2("/data/data/com.android.my_app/databases/my_db.db"‌​, &handle, 1, NULL) failed

1 个答案:

答案 0 :(得分:0)

使用它来检查数据库

     private boolean checkDataBase() {
    // TODO Auto-generated method stub
       File dbFile = new File(DB_PATH + DB_NAME);
       return dbFile.exists();
  }
    where  path
    private static String DB_PATH = "/data/dat/your_package_name/databases/";
    and  DB_NAME is database name