Java 序列号为的JDBC insert的列索引无效
下面是我的代码: 我将三个参数传递给insertRecordIntoTable方法,该方法将执行JDBC insert查询,但接收到无效的列索引 以下是打印的日志语句: insertRecordIntoTable内部 序列14的ID 无效的列索引Java 序列号为的JDBC insert的列索引无效,java,jdbc,Java,Jdbc,下面是我的代码: 我将三个参数传递给insertRecordIntoTable方法,该方法将执行JDBC insert查询,但接收到无效的列索引 以下是打印的日志语句: insertRecordIntoTable内部 序列14的ID 无效的列索引 private static void insertRecordIntoTable(String userName, String targetEmail, String siteName) throws SQLException {
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变量两次
preparedStatement.executeQuery("SELECT id_....);
为此查询创建并使用另一个变量,否则将覆盖原始查询
也考虑如果
会发生什么if ( srs!=null && srs.next() ) {
返回false谢谢。我已经创建了一个新的preparedStatement变量,它成功了!