I am trying to get the id
of the inserted row. Currenly I am not getting the id
back and I am getting the exception java.sql.SQLException: Column 'route_id' not found.
but when I query it as in the commented code I am getting it but it is of all rows in the routes
table. How can I fix it?
I appreciate any help.
Code:
if (routesTables.next()) {
PreparedStatement prepRoutesInsert = con.prepareStatement(
"INSERT INTO routes(direction, route)"
+ "VALUES( ?, ?)",
Statement.RETURN_GENERATED_KEYS);
prepRoutesInsert.setString(1, direction);
prepRoutesInsert.setInt(2, route);
prepRoutesInsert.executeUpdate();
// PreparedStatement prepRoutesInsert2 =
// con.prepareStatement(
// "SELECT route_id from routes");
// ResultSet rs = prepRoutesInsert2.executeQuery();
// while(rs.next()){
// int route_id2 = rs.getInt("route_id");
// System.out.println(route_id2);
// }
try (ResultSet generatedKeys = prepRoutesInsert
.getGeneratedKeys()) {
if (generatedKeys.next()) {
int id = generatedKeys.getInt("route_id");
System.out.println("The id is: " + id);
}
}
}
routes table:
stt.execute("CREATE TABLE IF NOT EXISTS routes ("
+ "route_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
+ "direction VARCHAR(30) NOT NULL, "
+ "route INT(11) NOT NULL )");