【问题标题】:How to compare id with the table column values in local database?如何将 id 与本地数据库中的表列值进行比较?
【发布时间】:2018-02-02 14:14:24
【问题描述】:

现在我需要检查planid 与本地数据库中的表值。

如果存在,那么它应该返回true。否则返回false。 我从 java 类调用这个方法并像这样存储值。

布尔计划 = dbHandler.IsplanExisted(app_plan_id);

DatabaseModule.java 中的方法

public Boolean IsplanExisted(int planID) {
    SQLiteDatabase db = null;
    Cursor c = null;
    try {
        String qry = "SELECT * FROM " + Table_Plan_App + " WHERE " + 
PAPP_Plan_ID + " = " + "\"" + planID + "\"";
        db = this.getReadableDatabase();
        if (db.isOpen()) {
            c = db.rawQuery(qry, null);
            c.moveToFirst();
            if (c.getCount() > 0)
                return true;
            else
                return false;
        } else
            return false;
    } catch (Exception e) {
        Log.d("eEmp/DBUserExisted", e.toString());
        return false;
    } finally {
        if (c != null)
            c.close();
        if (db != null)
            db.close();
        ;
    }
}

我正在将我的app_plan_id 与表中的PAPP_Plan_ID 进行比较。

我的问题是方法总是在这里返回true

如果 (c.getCount() > 0) 返回真;

为什么?

我是安卓新手。任何帮助将不胜感激。

【问题讨论】:

    标签: java android sql sqlite


    【解决方案1】:
    if (c.getCount() > 0) return true; 
    

    为什么?

    因为,您的表至少有 1 行,c.getCount() 返回总行数。

    【讨论】:

    • 但是没有行。即使 c.getCount>0 返回 true@Ravi
    【解决方案2】:

    我相信您显示的代码会返回正确的结果,而您遇到的问题是您的后续代码;根据您的评论:-

    但是没有行。即使 c.getCount>0 返回 true

    出于测试目的,我使用了:-

    DBHelper2.java :-

    公共类 DBHelper2 扩展 SQLiteOpenHelper {

    public static final String DBNAME = "planning";
    public static final int DBVERSION = 1;
    public static final String Table_Plan_App = "planapp";
    public static final String PAPP_Plan_ID = "planpp_id";
    public static final String other_column = "planapp_other";
    
    public DBHelper2(Context context) {
        super(context, DBNAME, null, DBVERSION);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("ONCREATE","Initiated");
        String crtsql = "CREATE TABLE IF NOT EXISTS " + Table_Plan_App +
                "(" +
                PAPP_Plan_ID + " INTEGER, " +
                other_column + " TEXT" +
                ")";
        Log.d("ONCREATE","Createing table using SQL " +crtsql);
        db.execSQL(crtsql);
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
    }
    
    public long insertPlan(int id, String other) {
        long rv = -1;
        SQLiteDatabase db =  this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(PAPP_Plan_ID,id);
        cv.put(other_column,other);
        rv = db.insert(Table_Plan_App,null,cv);
        db.close();
        return rv;
    }
    
    public Boolean IsplanExisted(int planID) {
        String tag = "ISPLANEXISTED";
        SQLiteDatabase db = null;
        Cursor c = null;
        try {
            String qry = "SELECT * FROM " + Table_Plan_App + " WHERE " +
                    PAPP_Plan_ID + " = " + "\"" + planID + "\"";
            Log.d(tag,"Generated query is " + qry);
            db = this.getReadableDatabase();
            Log.d(tag,"Readable Database obtained.");
            if (db.isOpen()) {
                Log.d(tag,"Database is open.");
                c = db.rawQuery(qry, null);
                String[] columns = c.getColumnNames();
                for (String s: columns
                     ) {
                    Log.d(tag,"Column " + s);
    
                }
                Log.d(tag,"Query completed");
                c.moveToFirst();
                Log.d(tag,"Moved to fist attempt completed.");
                Log.d(tag, "Cursor row count is " + c.getCount());
                if (c.getCount() > 0) {
                    Log.d(tag, "Returning True");
                    return true;
                } else {
                    Log.d(tag,"Returning false as count is not greater than 0.");
                    return false;
                }
            } else
                Log.d(tag,"Oooops Database is not open.");
                return false;
        } catch (Exception e) {
            Log.d("eEmp/DBUserExisted", e.toString());
            e.printStackTrace();
            return false;
        } finally {
            Log.d(tag,"Closing Cursor and Database in Finally construct.");
            if (c != null)
                c.close();
            if (db != null)
                db.close();
            ;
        }
    }
    

    }

    注意事项

    • IsplanExisted 方法中添加了大量的日志记录/调试代码,否则IsplanExisted 的代码是相同的。

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            DBHelper2 dbhlp2 = new DBHelper2(this);
            boolean result;
            // First delete all rows from table
            dbhlp2.getWritableDatabase().delete(DBHelper2.Table_Plan_App,null,null);
    
            // Try with no rows in table
            result = dbhlp2.IsplanExisted(100);
            Log.d("TESTRESULT", "Result from IsplaneExpired(ID 100 table empty) was " + String.valueOf(result));
    
            // Add a row with id as 12
            dbhlp2.insertPlan(12,"test1");
    
            // Check for row with id of 20 (shouldn't be one)
            result = dbhlp2.IsplanExisted(20);
            Log.d("TESTRESULT", "Result from IsplaneExpired(ID 20 no such row) was " + String.valueOf(result));
            // Check for row with id 12 (should exist)
            result = dbhlp2.IsplanExisted(12);
            Log.d("TESTRESULT", "Result from IsplaneExpired(ID 12 should exist) was " + String.valueOf(result));
    
        }
    }
    

    注意事项

    • 获取DBHelper2的实例,然后使用IsPlanExisted方法将调试信息写入日志。

    结果:-

    第 1 部分 - 空表,因此没有行 - 按预期返回 false。

    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Generated query is SELECT * FROM planapp WHERE planpp_id = "100"
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Readable Database obtained.
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Database is open.
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Column planpp_id
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Column planapp_other
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Query completed
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Moved to fist attempt completed.
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Cursor row count is 0
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Returning false as count is not greater than 0.
    02-02 21:54:32.530 1782-1782/? D/ISPLANEXISTED: Closing Cursor and Database in Finally construct.
    02-02 21:54:32.530 1782-1782/? D/TESTRESULT: Result from IsplaneExpired(ID 100 table empty) was false
    

    第 2 部分 - 添加 id 为 12 的行后,查找 id 20 - 如预期的那样为 false。

    02-02 21:54:32.534 1782-1782/? D/ISPLANEXISTED: Generated query is SELECT * FROM planapp WHERE planpp_id = "20"
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Readable Database obtained.
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Database is open.
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Column planpp_id
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Column planapp_other
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Query completed
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Moved to fist attempt completed.
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Cursor row count is 0
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Returning false as count is not greater than 0.
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Closing Cursor and Database in Finally construct.
    02-02 21:54:32.538 1782-1782/? D/TESTRESULT: Result from IsplaneExpired(ID 20 no such row) was false
    

    第 3 部分 - 查找 id 为 12 的行 - 按预期找到。

    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Generated query is SELECT * FROM planapp WHERE planpp_id = "12"
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Readable Database obtained.
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Database is open.
    02-02 21:54:32.538 1782-1782/? D/ISPLANEXISTED: Column planpp_id
    02-02 21:54:32.542 1782-1782/? D/ISPLANEXISTED: Column planapp_other
    02-02 21:54:32.542 1782-1782/? D/ISPLANEXISTED: Query completed
    02-02 21:54:32.542 1782-1782/? D/ISPLANEXISTED: Moved to fist attempt completed.
    02-02 21:54:32.542 1782-1782/? D/ISPLANEXISTED: Cursor row count is 1
    02-02 21:54:32.542 1782-1782/? D/ISPLANEXISTED: Returning True
    02-02 21:54:32.542 1782-1782/? D/ISPLANEXISTED: Closing Cursor and Database in Finally construct.
    02-02 21:54:32.542 1782-1782/? D/TESTRESULT: Result from IsplaneExpired(ID 12 should exist) was true
    

    更简单/精简的替代方案

    IsplanExisted 可以简化为:-

    public boolean IsplanExisted(int planID) {
    
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor c = db.query(
                Table_Plan_App,
                null,
                PAPP_Plan_ID + "=?",
                new String[]{String.valueOf(planID)},
                null,null,null
        );
        int count = c.getCount();
        c.close();
        return count > 0;
    }
    

    注意事项

    • getReadableDatabase 通常会返回一个可写的数据库,因此最好始终使用 getWriteableDatabase :-

    创建和/或打开数据库。这将是返回的相同对象 通过 getWritableDatabase() 除非出现问题,例如磁盘已满, 要求以只读方式打开数据库。在这种情况下,一个 将返回只读数据库对象。如果问题得到解决,则 未来对 getWritableDatabase() 的调用可能会成功,在这种情况下 只读数据库对象将被关闭并且读/写对象 将来会被退回。 getReadableDatabase

    • 在一个简单的应用程序中没有真正需要关闭数据库,所以db.close 被省略了。完成后应该关闭光标。
    • 使用方便(通常首选)query 而不是rawQuery。这将构建查询,它将根据需要转义字符(PS 无需将 ID 括在引号中)。
    • 第三个参数是WHERE子句少WHERE。它可以包含使用 ? 的参数化参数,然后由第四个参数指定要使用的参数/值的字符串数组。
    • query

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多