Until sometime back, I was unaware of how I could get the value of an auto-incremented field after an Insert Statement. But recently I needed it for two of my projects simultaneously, so I explored the possibilities. As one of my project is in Java and other is in PHP, we will go through both of them. So, here is the problem. In general, the PRIMARY KEY field is the AUTO_INCREMENT field. Now wen you insert a row, a new key is generated and you can’t get it through usual way as this row can be accessed only using the primary key. So here is how it can be done:In JAVA:
/*Insert a row into the desired table that generates
an auto increment field*/stmt.executeUpdate("Insert into tableName (col1, col2) values (val1, val2)", Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys();int autoIncValue = -1;if(rs.next())
{
autoIncValue = rs.getInt(1);
/*You can get more generated keys if they are generated in your code*/
}Read more: Public Mind
/*Insert a row into the desired table that generates
an auto increment field*/stmt.executeUpdate("Insert into tableName (col1, col2) values (val1, val2)", Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys();int autoIncValue = -1;if(rs.next())
{
autoIncValue = rs.getInt(1);
/*You can get more generated keys if they are generated in your code*/
}Read more: Public Mind
0 comments:
Post a Comment