我试图通过asp.net应用程序返回最后插入的标识值。我一直在弄1.我做错了什么?
代码:
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{}
}
答案 0 :(得分:1)
ExecuteNonQuery
返回受影响的行数。您必须改为使用ExecuteScalar
。
ID = (int) command.ExecuteScalar();