I am trying to return the last inserted identity value through an asp.net application. I keep getting 1. What am I doing wrong?
Code:
string ID="";
const string statement = "INSERT INTO asp2(CustomerName,Email,CP,CPN) VALUES(@text1,@text2,@text3,@text4);SELECT SCOPE_IDENTITY()";
using (var command = new SqlCommand(statement))
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ST"].ConnectionString))
{
try
{
command.Parameters.AddWithValue("@text1", TextBox1.Text);
command.Parameters.AddWithValue("@text2", TextBox4.Text);
command.Parameters.AddWithValue("@text3", TextBox2.Text);
command.Parameters.AddWithValue("@text4", TextBox3.Text);
connection.Open();
command.Connection = connection;
ID = command.ExecuteNonQuery().ToString();
connection.Close();
}
catch{}
}
ExecuteNonQuery
returns number of affected rows. You must use ExecuteScalar
instead.
ID = (int) command.ExecuteScalar();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.