Java ResultSet跳过记录

时间:2016-08-17 17:21:31

标签: java mysql

经过一个早上的研究,我很难理解应该是一段简单的代码。

我想要的只是从测试数据库中的raw_material表中获取所有记录。

这是我正在做的事情:

public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
        // TODO Auto-generated method stub

    //get our stuff first - raw materials and doc names and paths
    try {

        Connection conn = user.getConnection();
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0");

        do {
        String result = rs.getString("raw_material_number").toString();
        System.out.println("next item: " + result);
        //ithosList.add(rs.getString("raw_material_number"));
        } while(rs.next());
    }

     catch (Exception e) {
       ithosList.equals(null);
        System.out.println("DB error : " + e);
     }
}

以下是mySQL中的结果:

Result

所以我希望第一个“结果”为MAN-500-121200000,但显示为RAW-001485

我无法在代码中看到我正在“跳过”第一条记录的任何地方,但如果我放手,它会跳过下一条记录到MAN-500-056100000

我使用了错误的用户连接吗?这是我能看到的唯一影响这一点的东西。

我认为user.getConnection()只针对常规测试数据库。

3 个答案:

答案 0 :(得分:4)

您的代码似乎不正确,预期的循环是:

while(rs.next()) {
    String result = rs.getString("raw_material_number");
    System.out.println("next item: " + result);
}

考虑使用try-with-resources语句正确关闭您的ConnectionStatementResultSet作为下一个:

try (Connection conn = user.getConnection();
     Statement st = conn.createStatement();
     ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0")) {
    // My code here
}

答案 1 :(得分:0)

试试这样。

while(rs.next()){
  String result = rs.getString("raw_material_number");
  System.out.println("next item: " + result);
}

答案 2 :(得分:0)

public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
    // TODO Auto-generated method stub
    int i = 1;
    //get our stuff first - raw materials and doc names and paths
    try {

        Connection conn = user.getConnection();
        Statement st = conn.createStatement();
        ResultSet rsCount = st.executeQuery("SELECT COUNT(*) from raw_material");
        rsCount.first();
        long r = (Long) rsCount.getObject(i);

        for (i=1; i < r+1; i++) {

            ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id =" + i + "");

            //moves to the first record
            rs.first();

            do {
                String result = rs.getString("raw_material_number");
                System.out.println("next item: " + result);
                ithosList.add(rs.getString("raw_material_number"));
            } while(rs.next());
        }
    }

    catch (Exception e) {
        ithosList.equals(null);
        System.out.println("DB error : " + e);
    }

}

Hacky做这件事的方式,但现在让它起作用,至少在高级开发人员从丧亲之痛返回之前。请记住,我只有3个月的java,受到了火的洗礼。洛尔。