带有序列号的JDBC插入的列索引无效

时间:2018-02-13 07:06:38

标签: java jdbc

以下是我的代码: 我将三个参数传递给方法insertRecordIntoTable,它将执行JDBC插入查询,但我收到了无效的列索引。

以下是打印的日志声明:

在insertRecordIntoTable内部

序列14中的ID

列索引无效

private static void insertRecordIntoTable(String userName, String targetEmail, String siteName) throws SQLException {

        Connection dbConnection = null;
        PreparedStatement preparedStatement = null;
        System.out.println("Inside insertRecordIntoTable ");
        String insertTableSQL = "insert into TableName values(?,?,?,?,?)";

        try {
            dbConnection = getDBConnection();
            preparedStatement = dbConnection.prepareStatement(insertTableSQL);

                        ResultSet srs = preparedStatement.executeQuery("SELECT id_seq.NEXTVAL FROM dual");
                if ( srs!=null && srs.next() ) {
                    int myId = srs.getInt(1);
                    System.out.println("ID from sequence "+myId);
                    preparedStatement.setInt(1, myId);
                    System.out.println("Inserted ID value "+myId);
                    srs.close();
                }

                preparedStatement.setString(2, userName);
                System.out.println("Inserted username value "+userName);

                preparedStatement.setString(3, targetEmail);
                System.out.println("Inserted targetEmail value "+targetEmail);

                preparedStatement.setString(4, siteName);
                System.out.println("Inserted sitecode value "+siteName);

                preparedStatement.setTimestamp(5, getCurrentTimeStamp());
                System.out.println("Inserted date value "+getCurrentTimeStamp());

                preparedStatement .executeUpdate();

                System.out.println("Inserted values ");
                System.out.println("Inserted name & email into the table..."); 

            // execute insert SQL stetement
            preparedStatement.executeUpdate();

            System.out.println("Record is inserted into DBUSER table!");

        } catch (SQLException e) {

            System.out.println(e.getMessage());

        } finally {

            if (preparedStatement != null) {
                preparedStatement.close();
            }

            if (dbConnection != null) {
                dbConnection.close();
            }

        }
        }

1 个答案:

答案 0 :(得分:1)

您正在使用相同的PreparedStatement变量两次

   while (line != null) {

        line = reader.readLine();
        if(!line.contains("END")){
            key += line;
        }else{

            //Note that you can use split logic like below, or use java substring
            String[] words = line.split("");
            for(String s : words){
                if(s.equals("END")){
                    return key;
                }
                key += s;
            }
        }
    }

为此Query创建并使用另一个变量,否则将覆盖原始查询。

还要考虑如果

会发生什么
preparedStatement.executeQuery("SELECT id_....);

返回false