在openDatabase之后尝试getReadable时,数据库未打开错误

时间:2013-11-28 07:10:36

标签: android sqlite

执行此代码后,符合mydb = this.getReadableDatabase();错误表示“数据库未打开”。什么原因?

  private SQLiteDatabase mydb;

        public Cursor select(String table,String where){
            mydb.openDatabase(DATABASE_PATH, null, 1);
            mydb =this.getReadableDatabase();
            String sql = "SELECT * FROM "+table+" WHERE "+where;
            xLog.info(sql);

            Cursor result=null;
            try {
                result = mydb.rawQuery("SELECT * FROM "+table+" WHERE "+where, null);
            } catch (Exception e) {
                xLog.error(e.getMessage());
            }
            return result;
        }

这是整个数据库类,当然我已经简化了它并删除了不必要的数据:

public class DbHelper extends SQLiteOpenHelper{
    private SQLiteDatabase mydb;
//    private static DbHelper sInstance = null;
      private static final String DATABASE_NAME = "shareholders.db";
      private static final String DATABASE_PATH = "/data/data/com.example.shareholders/databases/shareholders.db";



    public DbHelper(Context context) {
        super(context, "shareholders.db", null, 1);
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            sql = "CREATE TABLE IF NOT EXISTS settings (name text,value text)";
            db.execSQL(sql);


        } catch (Exception e) {
            xLog.error(e.getMessage());
        }


        ContentValues cv = new ContentValues()

        cv.clear();
        cv.put("name", "picture");
        cv.put("value", "");
        db.insert("settings", null, cv);

        db.close();

    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    public Cursor selectAll(String table){
        mydb.openDatabase(DATABASE_PATH, null, 1);
        mydb =this.getReadableDatabase();
        String sql = "SELECT * FROM "+table;
        xLog.info(sql);
        Cursor result=null;
        try {
            result = mydb.rawQuery(sql, null);
        } catch (Exception e) {
            xLog.error(e.getMessage());
        }
        return result;
    }
}

1 个答案:

答案 0 :(得分:0)

根据您的代码

DbHelper helper = new DbHelper(context);
mydb = helper.getReadableDatabase();

这不是在Android中实施数据库评估的最佳方式。