【问题标题】:How to find that a SQL query executed has returned nothing?如何发现执行的 SQL 查询没有返回任何内容?
【发布时间】:2011-04-01 05:55:54
【问题描述】:
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
public class searchlink{
public static void main(String args[]) throws Exception {
    //String link="http://hosted.ap.org";
    Connection con=null;
    Statement stmt=null;
    Statement stmtR=null;
    if(con==null){
            SQLConnection.setURL("jdbc:sqlserver://192.168.2.53\\SQL2005;user=sa;password=365media;DatabaseName=LN_ADWEEK");
            con=SQLConnection.getNewConnection();
            stmt=con.createStatement();
            stmtR=con.createStatement();
    }
    ResultSet rs;
    rs=stmt.executeQuery("select url from urls where url='http://www.topix.com/rty/elyria-oh'");
    while(rs.next()){
    String mem=rs.getString(1);
    System.out.println("Result is "+mem);}
}
}

如果查询返回一行,上述程序将打印输出。 如果查询没有返回任何内容,程序将停止而不打印任何内容。

我希望程序能够识别查询没有返回任何内容,并打印出类似“SQL 查询执行后没有返回任何内容”的输出,而不是停止它而不打印任何内容。

如何使用一些方法或变量来识别查询已经执行而不返回任何行?

【问题讨论】:

    标签: java jdbc


    【解决方案1】:
    if (rs.hasNext())
    {
        while(rs.next())
       {
        String mem=rs.getString(1);
        System.out.println("Result is "+mem);
       }
    
    }
    else
    {
       System.out.println("There is nothing returned after SQL query execution ");
    }
    

    也许吧~

    【讨论】:

    • 我不相信 ResultSet 会为空,而是实例化并为空。
    • 还是不对。 “rs.next()”会将其移至下一行。你的意思是“rs.hasNext()”
    【解决方案2】:

    第一个 (rs.next()) 将告诉您是否返回了任何数据。对那个做出反应,然后遍历其余部分(如果有的话)。

    下面我将当有一行时要做什么的逻辑提取到一个单独的方法中,然后在“if”之后和每个“where”中调用它。

       . . .
    
    
       ResultSet rs;
       rs=stmt.executeQuery("select url from urls where url='http://www.topix.com/rty/elyria-oh'");
       if (rs.next() {
          printRow(rs);
          while(rs.next()){
              printRow(rs);
          }
        }
        else {
            System.out.println("no data returned");
        }
      }
    
      static public printRow(ResultSet rs) {
        String mem=rs.getString(1);
        System.out.println("Result is "+mem);}
      }   
    
    }
    

    【讨论】:

      【解决方案3】:
      boolean hasRows = false;
      while(rs.next()){
        hasRows = true;
        // do other stuff required.
      }
      
      if(!hasRows)
      {
        // do stuff when no rows present.
      }
      

      -- 或--

      if(!rs.next())
      {
        // do stuff when no rows prsent.
      }
      else
      {
        do{
        // do stuff required
        }while(rs.next());
      }
      

      请记住,检查 if(!rs.next()) 将使光标在结果集中前进。在获得值之前不要再次推进它。

      【讨论】:

      • +1 优雅的第二个版本。不幸的是,逻辑更难阅读,而且你漏掉了一个分号。
      • @tc 谢谢,有那个分号,我总是在做的时候忘记它们。我同意在第二个例子中你在做什么并不是很明显。与其他任何事情一样,这完全取决于个人品味和团队标准,您选择在可读性/优雅范围的哪一边出错(尽管幸运的是它们并不总是相互排斥的)。
      【解决方案4】:

      在循环中放置一个计数器...

      int count = 0;
      
      while ( rs.next() )
      {
          count++;
      
          String mem=rs.getString(1);   
          System.out.println("Result is "+mem);}
          .
          .
          .
      }
      

      然后...

      if (count==0)
      {
          // show your message "There is nothing returned after SQL query execution"
      }
      

      rs.next() 的任何调用都会移动光标,因此if (rs.next() == false) 会在您有 2 个或更多结果时让您领先并让您跳过第一个结果,如果您有一个结果则完全错过它。

      祝你好运,

      瑞克

      【讨论】:

      • 如果返回 2**32 行则失败。
      • 恕我直言,while(rs.next()) 语句适用于 0,1,许多结果...对于 1 或更多的任何场景,计数都会增加,因此测试计数为非零给出您找到 1 条或多条记录或没有的答案。至少在我看来是这样。瑞克
      【解决方案5】:
      boolean got_result = false;
      while (...) {
        got_result = true;
        ...
      }
      if (!got_result) {
        ...
      }
      

      【讨论】:

        【解决方案6】:

        正常的 JDBC 习惯用法是将结果收集到像 List<Entity> 这样的集合中。另一个常见的习惯用法是在try-with-resources statement 中打开资源,以便它们正确地自动关闭。您的代码就是通过打开这些资源来泄漏数据库资源。如果您在短时间内重复运行此操作,则数据库将耗尽资源。

        这是一个启动示例:

        public List<Entity> list() throws SQLException {
            List<Entity> entities = new ArrayList<Entity>();
        
            try (
                Connection connection = database.getConnection();
                PreparedStatement statement = connection.prepareStatement("SELECT id, name, value FROM entity");
                ResultSet resultSet = statement.executeQuery();
            ) {
                while (resultSet.next()) {
                    Entity entity = new Entity(); 
                    entity.setId(resultSet.getLong("id"));
                    entity.setName(resultSet.getString("name"));
                    entity.setValue(resultSet.getInteger("value"));
                    entities.add(entity);
                }
            }
        
            return entities;
        }
        

        这样您就可以使用通常的List 方法来确定结果的状态:

        List<Entity> entities = entityDAO.list();
        
        if (entities.isEmpty()) {
            // It is empty!
        }
        else if (entities.size() == 1) {
            // It has only one row!
        }
        else {
            // It has more than one row!
        }
        

        另见:

        【讨论】:

        • 谢谢 Balus... 你的回答真的很有帮助而且非常简短。希望你能指导我,直到我成为一名优秀的 Java 程序员 :)
        【解决方案7】:
        if(!rs.isBeforeFirst())
           System.out.println("no data is returned");
        

        【讨论】:

          【解决方案8】:

          对于你可以做的选择查询

          rs.next();
          int value = resultSet.getInt(1);
          if (value == 0)
          {
                  //throw error message
          }
          else
                  // 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-07-17
            • 2020-09-25
            • 2018-02-18
            相关资源
            最近更新 更多