在Android中使用WHERE Clause SQLite数据库?

时间:2021-02-25 13:39:01

This is my code:

这是我的代码:

    public int getIdMotChuDe(String tenChuDe) {
            int IDChuDe = 0;
            try
            {
                Cursor c = null;
                c = database.rawQuery(
                    "SELECT ChuDeID FROM DanhSachChuDe WHERE TenChuDe = ?"
                     , new String[] {tenChuDe});
                c.moveToFirst();
                IDChuDe = c.getInt(c.getColumnIndex("ChuDeID"));
                c.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return IDChuDe;
        }

I'm trying to get ChuDeID from DanhSachChuDe table with condition in WHERE clause. But i don't know why this function always return 0. Help me please. Thanks! Sorry because my english.

我试图从DanhSachChuDe表中获取具有WHERE子句条件的ChuDeID。但我不知道为什么这个功能总是返回0.请帮帮我。谢谢!抱歉,因为我的英文。

1 个解决方案

#1


0  

This could be because an Exception is being thrown. The code you are using is not correctly checking the state of your Cursor - it attempts to moveToFirst() before any checking too see if the object is not null.

这可能是因为抛出异常。您正在使用的代码未正确检查Cursor的状态 - 它会在任何检查之前尝试moveToFirst(),同时查看该对象是否为null。

Your code also assumes a result is always returned. This is bad practise, and should be avoided. A much safer and more common solution is the following:

您的代码还假定始终返回结果。这是不好的做法,应该避免。更安全,更常见的解决方案如下:

if (cursor != null) {
    // If the cursor has results, move the cursor to first row
    if (cursor.moveToFirst()) {
        do {
            // YOUR METHODS HERE
            // then move to next row
        } while (cursor.moveToNext());
    }
}

#1


0  

This could be because an Exception is being thrown. The code you are using is not correctly checking the state of your Cursor - it attempts to moveToFirst() before any checking too see if the object is not null.

这可能是因为抛出异常。您正在使用的代码未正确检查Cursor的状态 - 它会在任何检查之前尝试moveToFirst(),同时查看该对象是否为null。

Your code also assumes a result is always returned. This is bad practise, and should be avoided. A much safer and more common solution is the following:

您的代码还假定始终返回结果。这是不好的做法,应该避免。更安全,更常见的解决方案如下:

if (cursor != null) {
    // If the cursor has results, move the cursor to first row
    if (cursor.moveToFirst()) {
        do {
            // YOUR METHODS HERE
            // then move to next row
        } while (cursor.moveToNext());
    }
}