I am trying to get the id
of the inserted raw in the routes
table. Currently I am getting the error Column 'route_id' not found
but the route and direction are being inserted in the table before Why am I getting this error?
Code:
DatabaseMetaData dbm = con.getMetaData();
ResultSet routesTables = dbm.getTables(null, null, "routes",
null);
int route_id;
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();
try (ResultSet generatedKeys = prepRoutesInsert
.getGeneratedKeys()) {
if (generatedKeys.next()) {
int id = generatedKeys.getInt("route_id");
System.out.println("The id is: " + id);
}
}
routes table structure:
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 )");
Screenshot of geratedKeys variable:
Edit:
When I query it like this I am getting the route_id
but of the all raws in the routes table:
PreparedStatement prepRoutesInsert2 =
con.prepareStatement(
"SELECT route_id from routes",
Statement.RETURN_GENERATED_KEYS);
ResultSet rs = prepRoutesInsert2.executeQuery();
while(rs.next()){
int route_id2 = rs.getInt("route_id");
System.out.println(route_id2);
}