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



以下是我的代码:我将三个参数传递给方法InserTrecordIntobable将执行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();
            }
        }
        }

您使用的是相同的准备变量

preparedStatement.executeQuery("SELECT id_....);

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

还考虑如果

会发生什么
if ( srs!=null && srs.next() ) {

返回false

最新更新