如何从查询中获得结果(mysql数据库)

xienkqul  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(392)

我正在给玩家排名,我需要把结果输入java。
我的密码是

public static int getRank(UUID uuid) throws SQLException {
    checkConnection();
    PreparedStatement s = con.prepareStatement(
            "SET @rownum := 0; SELECT rank FROM ( SELECT @rownum := @rownum + 1 AS rank, wins, uuid FROM `SKYWARS` ORDER BY wins DESC ) as result WHERE uuid=?");
    s.setString(1, uuid.toString());

    ResultSet r = s.executeQuery();
    r.next();
    return r.getInt(1);
}

但是s.execute()返回false,这意味着没有resultset。如何获取结果集?在mysql workbench中,它返回值rank和wins。
解决方案:我补充道 ?allowMultiQueries=true 连接语句。这使我的代码按原样工作。

hzbexzde

hzbexzde1#

@barmar提出了一个很好的解决方案:

public static int getRank(UUID uuid) throws SQLException {
    checkConnection();
    PreparedStatement s1 = con.prepareStatement(
            "SET @rownum := 0;");
    s1.execute();
    PreparedStatement s = con.prepareStatement(
            " SELECT rank FROM ( SELECT @rownum := @rownum + 1 AS rank, wins, uuid FROM `SKYWARS` ORDER BY wins DESC ) as rank WHERE uuid=?");
    s.setString(1, uuid.toString());
    if (!s.execute()) {
        System.out.println(123);
    } else {
        ResultSet r = s.executeQuery();
        r.next();
        return r.getInt(1);
    }
    return 0;
}

set语句可以拆分。

相关问题