Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I there any way to get the primary key value of the data we just added to the database table?? suppose we use the insert query:

string qry="insert into tbl_student(name,marksObtained,class,section) values("Arpan",50,"10","A")";

here the primary key is stud_id whose value is given automatically,
how can i retirve the value of stud_id which is recently updated to the database??
thank u for your help
Arpan
Posted

Try SELECT @@IDENTITY After the Insert/Update Query,
@@IDENTITY returns the value of first columns Last Inserted/Updated
 
Share this answer
 
Comments
amsainju 25-Aug-11 10:55am    
public static void insertNewStudent(string name,string clas,string section )
{
int STATUS;
SqlConnection con = GetConnection.getcon();
string qry = "insert into tbl_student(stud_name,stud_class,stud_section) values( @name,@clas,@section)";

SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@clas", clas);
cmd.Parameters.AddWithValue("@section", section);
STATUS= cmd.ExecuteNonQuery();
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
public static string getId()
{
string stud_id=null;
SqlConnection con = GetConnection.getcon();
string qry = "select @@IDENTITY";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
stud_id = sdr. ; //??????????????
break;
}
if (con.State == ConnectionState.Open)
{
con.Close();

}
return stud_id;

}

am i doing it right?? i can't figure out how i can retrive the data from sdr..
help
Raju Prajapati 12-Sep-11 5:55am    
SELECT @@IDENTITY write after insert query text and use cmd.ExecuteScalar() to return the ID. In place of writing another method return just return the ID in same method where your are inserting. But remember one thing that ExecuteScalar() returns object so you have to cast it properly as per your requirement
You can use Last_Insert_ID() function to get the last auto increment id. What I do is add the extra query to my command like this

C#
MySqlCommand cmd = new MySqlCommand("INSERT INTO tbl_student(name,marksObtained,class,section) VALUES ('Arpan',50,'10','A'); LAST_INSERT_ID();", connection);
           int lastID = (int)cmd.ExecuteScalar();


Here
[^] is the reference manual link.

Hope this helps
 
Share this answer
 
v2
Comments
amsainju 25-Aug-11 10:37am    
does it help with mssql..that was the reference for mysql
Wayne Gaylard 26-Aug-11 2:03am    
My apologies. I read that as MySQL. Sorry!
amsainju 25-Aug-11 10:52am    
it didn't work it said error near LAST_INSERT_ID

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900