java.sql.SQLException:在结果集开始之前。结果集循环中的查询如何?

时间:2013-05-07 21:37:55

标签: java mysql jdbc

我正在尝试在结果集循环中创建查询,但我一直收到错误“在结果集开始之前”。我尝试了很多不同的方法,但他们不断提出相同的错误。

有人可以帮助我吗?

String insertSQL = "INSERT INTO MonthlyReportTable VALUES(NULL,"; //Primary Key.

String PlannetSchemeCode = "";
int ResponcibleAuthorityID = 0;

Statement stmt = ConnectionDetails.getNewConnectionPPARSDB().createStatement();
ResultSet resultsSet = stmt.executeQuery("SELECT * FROM planning_scheme");

Statement insideStatement = ConnectionDetails.getNewConnectionPPARSDB().createStatement();

//Loop though each planning scheme and create the data for each field.
while (resultsSet.next()) 
{
    PlannetSchemeCode = "'" + resultsSet.getString("ps_code") + "'";

    //Planning Scheme Primary Key
    insertSQL += PlannetSchemeCode + ",";

    /*
    //Responsible Authority ID
    insertSQL += "'" + String.valueOf(
            ResponcibleAuthorityID = MySQLUtil.getResults(
                ConnectionDetails.Database_Connection_PPARSDB, 
                "SELECT resp_authority_id " +
                "FROM resp_authority_to_ps " +
                "WHERE ps_code = " + PlannetSchemeCode
            )
            .getInt("resp_authority_id")
        ) + "'";
    */

    ResultSet insideResultsSet = 
            insideStatement.executeQuery(
                "SELECT resp_authority_id " +
                "FROM resp_authority_to_ps " +
                "WHERE ps_code = " + PlannetSchemeCode
            );

    //ERROR HERE, some reason results set is getting set wrong??
    //Error here, this current results set is resetting the Results set.
    ResponcibleAuthorityID = insideResultsSet.getInt("resp_authority_id");

    //Total_Received_CM

    //Add the rest of the values temporary.
    int FeildsAdded = 3;
    for(int i = 1 + FeildsAdded; i < 458; i++)
    {
        insertSQL += String.valueOf(0) + ",";
    }

    //Insert date and end SQL string.
    insertSQL += "NOW()";
    insertSQL += ")";

    System.out.println(insertSQL);

    //Do Insert in PPARS.
    //stmt.executeQuery(insertSQL);
    //Reset the SQL String for the new Row.
    insertSQL = "INSERT INTO MonthlyReportTable VALUES(NULL,";
}

1 个答案:

答案 0 :(得分:8)

  

ResultSet光标最初位于第一行之前;第一次调用方法next使第一行成为当前行;第二个调用使第二行成为当前行,依此类推。

您需要先致电ResultSet#next(),然后才能阅读返回的数据。

ResultSet insideResultsSet = insideStatement.executeQuery(
    "SELECT resp_authority_id " +
    "FROM resp_authority_to_ps " +
    "WHERE ps_code = " + PlannetSchemeCode
);

if (insideResultsSet.next()) {
    ResponcibleAuthorityID = insideResultsSet.getInt("resp_authority_id");

    // etc...
}