MySQL,在结果集开始之前

时间:2014-01-14 16:35:01

标签: java mysql

我收到错误在开始结果集之前我认为在从ResultSet检索数据之前我必须在ResultSet上使用next()?

public void getPersonsOrders(String firstName){
    Connection con = connect();                                                                                             
    try{
        Statement s = con.createStatement();
        s.executeUpdate("use stl;");
        ResultSet rs1 = s.executeQuery("select personID from person where first_name = " +"'"+firstName+"'"+";");       //get persons ID no.
        ResultSet rs2 = s.executeQuery("select * from orderr where personID = "+rs1.getInt(1)+";");             //use ID no. to 
        rs2.next();
        for(int i = 1; i < 4; i++){                                                                             //retrive order
            System.out.println(rs2.getInt(i));
        }
    }
    catch(SQLException e){
        System.out.println("3" +e.getMessage());
    }
}

3 个答案:

答案 0 :(得分:0)

你应该执行

rs1.next();

ResultSet rs2 = s.executeQuery("select * from orderr where personID = "+rs1.getInt(1)+";"); 

请记住,您应该关闭已打开的资源。

问候。

答案 1 :(得分:0)

您可以使用以下机制。

resultSet=s.executeQuery("select personID from person where first_name = " +"'"+firstName+"'"+";");

            if (resultSet!= null)
            {

                do
                {
                   //You can code your business logic here by getting data from db like:

                 System.out.println(resultSet.getString("first_name"));
                } while (resultSet.next());

答案 2 :(得分:0)

在使用rs1.next()读取之前,您不会致电rs1.getInt(1)

顺便说一句,您可以使用join的单个SQL语句执行此操作:

SELECT orderr.* FROM orderr JOIN person ON orderr.personID = person.personID WHERE person.first_name = ?

你也应该使用这样的java.sql.PreparedStatement

PreparedStatement preparedStatement = connection.prepareStatement("SELECT orderr.* FROM orderr JOIN person ON orderr.personID = person.personID WHERE person.first_name = ?");
preparedStatement.setString(1, firstName);

ResultSet resultSet = preparedStatement.executeQuery();

数据库将缓存查询计划,这将有助于提高性能,还可以防止SQL注入攻击。