参数化查询中的数据类型不兼容? (Java)

Incompatible data type in parameterized query? (Java)

我目前正在开发一个应用程序,该应用程序使用 SQL 数据库来存储用户的帐户信息(用户名、密码等)。在应用程序中,既有普通用户,也有管理员用户。我还使用了一个参数化查询,这对我来说还是很新鲜的,以检查用户的管理员状态。 users table 的 onCreate() 方法(这是我用来存储用户信息的方法)如下所示。

public void onCreate(SQLiteDatabase myDB) {
    myDB.execSQL("create Table users(username Text primary key, password Text, email Text, 
    phone Text, admin Integer, userID Text)");
}

因此,如您所见,admin 列存储了一个整数。在我的应用程序上下文中,0 表示非管理员用户,1 表示管理员用户。我正在使用参数化查询来检查某个用户是否存在于 users table 中并且还具有管理员身份(如果他们的管理员列中的整数为 1)。检查用户是否为管理员的代码如下所示。

// returns true if user is an admin, false if non-admin
public boolean checkAdmin(String username) {
    SQLiteDatabase myDB = this.getWritableDatabase();
    Cursor cursor = myDB.rawQuery("select * from users where username = ? and admin = ?", new String[] {username,1});
    if (cursor.getCount()>0) // cursor > 0 if user exists in the database and has admin status
        return true;
    else
        return false;
}

本质上 SQL 查询只是 select * from users where username = username and admin = 1,但我 运行 遇到的问题在 new String[] {username,1}。 “1”参数带有红色下划线,Android Studio 告诉我所需的类型是字符串。同样,我对参数化查询还是陌生的,我很困惑为什么当 admin 数据类型为 int 时会出现这样的错误。

您正在声明一个字符串数组新字符串[]尝试将 1 添加为字符串。

Cursor cursor = myDB.rawQuery("select * from users where username = ? and admin = ?", new String[] {username,"1"});