如何使用asp和sql

时间:2015-05-19 15:57:27

标签: c# sql asp.net

我正在尝试使用以下代码获取最后插入行的值。我知道@@ IDENTITY和IDENTITY_SCOPE但是当我在asp参数化查询中编写代码时如何使用它们。

 SqlConnection MySQL = new SqlConnection(ConfigurationManager.ConnectionStrings["BloodDonorRegistrationConnectionString"].ToString());
            string BloodReq = "insert into Blood_Request(R_Name,R_Phone,R_Blood_Group,R_City,R_Address,Date,Time) values (@Name,@cell,@BGroup,@City,@Address,@date,@time)";

            SqlCommand Cmd = new SqlCommand(BloodReq, MySQL);
            Cmd.Parameters.AddWithValue("@Name", TextBoxName.Text);
            Cmd.Parameters.AddWithValue("@cell", TextBoxPhone.Text);
            Cmd.Parameters.AddWithValue("@BGroup", dropbownBlood.SelectedItem.Text);
            Cmd.Parameters.AddWithValue("@City", DropDownListCity.SelectedItem.Text);
            Cmd.Parameters.AddWithValue("@Address", TextBoxLocation.Text);
            Cmd.Parameters.AddWithValue("@date", DateTime.Now.Date);
            Cmd.Parameters.AddWithValue("@time", DateTime.Now.TimeOfDay);
            MySQL.Open();
            Cmd.ExecuteNonQuery();
            MySQL.Close();

请提前帮助并表示感谢。

3 个答案:

答案 0 :(得分:2)

使用cmd.ExecuteScalar代替Cmd.ExecuteNonQuery()。如果要返回更多值,也可以使用ExecuteReader

在您的Sql中使用{/ 1}},如

OUTPUT INSERTED.ID

答案 1 :(得分:1)

...    
string BloodReq = "insert into Blood_Request(R_Name,R_Phone,R_Blood_Group,R_City,R_Address,Date,Time) values (@Name,@cell,@BGroup,@City,@Address,@date,@time); SELECT SCOPE_IDENTITY() AS IID";

...
var insertedID = (Int32)Cmd.ExecuteScalar();

答案 2 :(得分:1)

使用scope_identity,基于您的代码的完整工作示例将是:

using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["BloodDonorRegistrationConnectionString"].ToString())) {
    int insertedID;
    var cmd = "insert into Blood_Request(R_Name,R_Phone,R_Blood_Group,R_City,R_Address,Date,Time) values (@Name,@cell,@BGroup,@City,@Address,@date,@time);SELECT CAST(scope_identity() AS int)";
    using (var insertCommand = new SqlCommand(cmd, con)) {
               insertCommand.Parameters.AddWithValue("@Name", TextBoxName.Text);
               insertCommand.Parameters.AddWithValue("@cell", TextBoxPhone.Text);
               insertCommand.Parameters.AddWithValue("@BGroup", dropbownBlood.SelectedItem.Text);
               insertCommand.Parameters.AddWithValue("@City", DropDownListCity.SelectedItem.Text);
               insertCommand.Parameters.AddWithValue("@Address", TextBoxLocation.Text);
               insertCommand.Parameters.AddWithValue("@date", DateTime.Now.Date);
               insertCommand.Parameters.AddWithValue("@time", DateTime.Now.TimeOfDay);
               con.Open();
               insertedID = (int)insertCommand.ExecuteScalar();
    }

}