【问题标题】:Type mismatch: cannot convert from void to int [duplicate]类型不匹配:无法从 void 转换为 int [重复]
【发布时间】:2014-09-09 15:09:56
【问题描述】:
public int countContacts() {
    String query = "select count(name) from contacts";
    int count = db1.execSQL(query);           //  I got error at this line
    return count;

}

我试图通过使用上面的代码来计算表中的行数。但是我收到了这个错误-“类型不匹配:无法从 void 转换为 int”。为什么会出现此错误,我该如何纠正?


更新:

db1 是 SQLiteDatabase。

我使用 Eclipse 进行编码。我在编码时遇到了这个错误。我什至没有运行代码。

【问题讨论】:

  • db1 有什么类型?你读过 JavaDoc 吗?
  • 什么是 db1?你能粘贴完整的代码吗?如果它是preparedStatement,则需要调用executeUpdate 而不是executeQuery
  • @talex 你所说的 db1 类型是什么意思?
  • 可以添加错误详情吗?
  • @Manu Jacob 每个变量都有一个与之关联的类型。您在声明变量时指定它。

标签: java android int void


【解决方案1】:

你不能使用 execSQL 来select

来自Android SDK documentation for SQLiteDatabase:

execSQL(String sql):执行单个 SQL 语句,该语句不是 SELECT 或任何其他返回数据的 SQL 语句。

你可以试试:

    //Query
    String query = "select COUNT from contacts where name = ?";
    Cursor cursor = db1.rawQuery(query, new String[] {name});
    if(cursor.getCount()<1) // title Not Exist
    {
        cursor.close();
        return 0;
    }
    cursor.moveToFirst();
    int count = cursor.getInt(cursor.getColumnIndex("COUNT"));
    cursor.close();
    return count;               

【讨论】:

  • 这段代码是否返回行数?
  • 是的。选择 COUNT 应该返回行数。
【解决方案2】:

您应该改用rawQuery

compileStatement(sql).simpleQueryForLong()

【讨论】:

    猜你喜欢
    • 2011-12-27
    • 2014-10-23
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多