如何检查ResultSet是否为空?

问题描述 投票:0回答:2

仅当选择查询返回至少一行时,我才尝试启动一个类。

我对以下查询功能的调用:

results=thequery("SELECT `username`,`numberpoints` FROM `highscores` WHERE `username` = '"+name+"'");//send query that checks if username exist     
                if(!results.next()) {
                BallTrial trial = new BallTrial();
                }

thequery函数:

public ResultSet  thequery(String query){

         PreparedStatement statement = null;
        ResultSet rs = null;

        Connection con=null;
        Statement st=null;
        try {
            con=DriverManager.getConnection("jdbc:mysql://localhost/scores","root","");

            statement = con.prepareStatement(query);

            rs=  statement.executeQuery();

            while(rs.next()){
                    System.out.println(rs.getString(1)+" "+rs.getString(2));

                    return rs;

            }}


        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("you have not accessed the data base");

        }

        return null;

    }

我在if(!results.next()) {处得到一个空指针异常,任何人都可以在这里澄清我的错误吗?

java mysql jdbc
2个回答
1
投票

您应在调用next之前添加空检查条件,该条件需要在行周围进行一些调整:results != null && !results.next()


1
投票

您需要进行一些更改:

  1. thequery方法中,返回ResultSet(即rs),而不是返回null。返回null将导致NPE。另外,请删除while(...),因为它需要由调用方完成,例如

    public ResultSet  thequery(String query){
    
     PreparedStatement statement = null;
     ResultSet rs = null;
    
     Connection con=null;
     Statement st=null;
     try {
         con=DriverManager.getConnection("jdbc:mysql://localhost/scores","root","");
         statement = con.prepareStatement(query);
         rs=  statement.executeQuery();
         return rs;
     catch (SQLException e) {
         e.printStackTrace();
         System.out.println("you have not accessed the data base");
         throw e;
     }
    }
    
  2. 在调用方方法中,通过调用rs.next()例如,检查ResultSet是否包含任何记录:

    results = thequery(..)
    if(!results.next()){
        BallTrial trial = new BallTrial();
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.