【问题标题】:ResultSet search Error in JDBCJDBC 中的结果集搜索错误
【发布时间】:2014-01-14 21:31:56
【问题描述】:

所以我是JDBC - SQL 编程 的初学者。我需要一点建议,很可能是关于 SYNTAX 的。

所以,问题 = 我正在尝试搜索记录中包含名称(函数参数中提供的字符串)的记录。以下是我的代码。现在我已经设计了这段代码,使得可以有超过 1 条同名记录,因此所有记录的数据都将被打印(通过 ShowData() 函数)。

protected static void SearchbyName (String toCompareName)
{
    Statement stmt = null;
    ResultSet rs = null;
    Connection conn = null;
    boolean flag = false;     //to confirm if record has found atleast once

    try
    {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection(url, username, password);    
        stmt = conn.createStatement();

        rs = stmt.executeQuery("SELECT idEmployee FROM employee WHERE name = ' "+toCompareName+" ' ");

        if( !(rs.next()) )    //if ResultSet is not empty
        {   
            while(rs.next())  //reading all records with the same name, extracted by Query
            {
                int foundID = rs.getInt("idEmployee");  //extracting ID of found record
                ShowRecord(foundID);        //prints record of foundID fromDB

                flag = true; //set flag
            }
        }
        if(flag==false) //if no record found
        {
            JOptionPane.showMessageDialog(null, "ERROR:: No Records Found..", "Not Found", JOptionPane.ERROR_MESSAGE);
        }

        //close connection
        if(rs!=null)
        {   rs.close();     }
        if(stmt!=null)
        {   stmt.close();   }
        if(conn!=null)
        {   conn.close();       }
    }
    catch(SQLException e)
    {   System.err.println(e);  }
    catch(Exception e)
    {   System.err.println(e);  }   

}

原来如此。据我了解,我正在执行的 RESULTSET rsQuery 存在一些问题. 请帮忙。 &如果您可以建议更好的搜索方法,请务必这样做。我将在相同的模式上编写另外 4 个函数 SearchbyAge、SearchbyQualification、SearchbySpecialization

【问题讨论】:

  • 但是你忘了说错误是什么:)
  • 您的显示数据功能也可能有错误。我会将查询打印到标准输出。然后,您可以在数据库窗口中复制并粘贴它,看看它是否有效。
  • @PeteBelford:先生,这种方法没用。我已经测试了我的 ShowData() 函数,它可以 100% 工作。

标签: java mysql sql jdbc resultset


【解决方案1】:

SOVLED

我的错误是在查询中。我在比较的字符串语法中添加了空格。

错误 = `"(.. WHERE name = " ' +toCompareName+ '" ");

正确 = `"(.. WHERE name = "'+toCompareName+'" ");

就是这样。希望它对其他人有帮助。 :)

【讨论】:

    【解决方案2】:

    这样就够了

     while(rs.next())  //reading all records with the same name, extracted by Query
                {
                    int foundID = rs.getInt("idEmployee");  //extracting ID of found record
                    ShowRecord(foundID);        //prints record of foundID fromDB
    
                    flag = true; //set flag
                }
    

    您不必使用if case 以这种方式检查结果集中的数据

    if( !(rs.next()) ) 
    

    这将移动到resultset中的下一条记录

    【讨论】:

    • 没用。我添加了一个system.out.print("In while loop");,但似乎控制没有进入这个循环。
    猜你喜欢
    • 2021-11-21
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2015-05-06
    • 2019-01-08
    相关资源
    最近更新 更多