使用Scope_identity和ExecuteNonScalar返回1?

时间:2014-03-11 11:17:11

标签: c# sql

我试图通过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{}
   }

1 个答案:

答案 0 :(得分:1)

ExecuteNonQuery返回受影响的行数。您必须改为使用ExecuteScalar

ID = (int) command.ExecuteScalar();