如何将id与本地数据库中的表列值进行比较?

时间:2018-02-02 14:14:24

标签: java android sql sqlite

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

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

  

boolean plan = 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返回。

  

if(c.getCount()> 0)                       return true;

为什么?

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

2 个答案:

答案 0 :(得分:0)

if (c.getCount() > 0) return true; 
     

为什么?

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

答案 1 :(得分:0)

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

  

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

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

DBHelper2.java: -

public class 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: -
  

创建和/或打开数据库。这将是返回的同一对象   by getWritableDatabase()除非出现一些问题,比如一个完整的磁盘,   要求数据库以只读方式打开。在那种情况下,a   将返回只读数据库对象。如果问题得到解决,a   将来调用getWritableDatabase()可能会成功,在这种情况下   将关闭只读数据库对象和读/写对象   将来会被退回。 getReadableDatabase

  • 没有必要在简单的App中关闭数据库,因此db.close被遗漏了。完成后,游标应该关闭。
  • 而不是rawQuery使用了query便利性(通常是首选的)?。这构建了查询,它将根据需要转义字符( PS,不需要将ID括在引号中)。
  • 第三个参数是WHERE子句减去WHERE。它可以包含使用 18, 812, 84, 34, 412, 87, 74 的参数化参数,然后由第四个参数指定要使用的参数/值的String数组。
  • 请参阅query