Click to See Complete Forum and Search --> : [RESOLVED] Get newly inserted row


hitai
February 28th, 2008, 07:45 PM
I`m using JDBC to connect to MySql. From my java code, I inserd new rows into the data table using INSERT statements. How can I get back the new inserted row? I`m leaving the fields to have their default values when inserting

hspc
February 29th, 2008, 03:03 AM
Hello, you can use the last_insert_id() MySQL function (If you use an autoincrement columns as a PK) to get the PK value of the newly added record.
Select col1,col2 from tablename where id = last_insert_id()
And read this data from java like this: (I'm not a java expert)

CallableStatement sql=con.prepareCall("call InsertAndGetValues()");

ResultSet result = sql.executeQuery();

if(result.first())
{
int x = result.getInt(1);
String s = result.getString(2);
}
InsertAndGetValues is the name of the stored procedure that you use to insert new recored and select its values as above.