如何在C#中执行存储过程?

时间:2019-04-19 19:00:00

标签: c# sql .net

使用以下SQL存储过程,如何在btnYes按钮的事件处理程序中执行它?我不知道如何执行存储过程。我设置了TextBox来输入RoomNo。当我单击btnYes时,预期结果应该是基于Occupiedtrue表中将tblRooms布尔值设置为RoomNo

CREATE PROCEDURE sproc_tblRooms_Update
    -- Parameters for the UPDATE statement
    @RoomNo   INT,
    @Occupied BIT
AS
    UPDATE tblRooms
    SET Occupied = @Occupied
    WHERE RoomNo = @RoomNo
在类中设置的

Update()方法:

public void Update(clsRoom RoomOccupancy)
{
    // This function will update an existing reservation in the database

    // Connect to the database
    clsDataConnection DBRoomVacancy = new clsDataConnection();

    // Add the parameters
    DBRoomVacancy.AddParameter("@RoomNo", RoomOccupancy.RoomNo);
    DBRoomVacancy.AddParameter("@Occupied", RoomOccupancy.Occupied);

    // Execute the query
    DBRoomVacancy.Execute("sproc_tblRooms_Update");
}

我要单击以执行存储过程的btnYes按钮的事件处理程序:

protected void btnYes_Click(object sender, EventArgs e)
{

}

2 个答案:

答案 0 :(得分:0)

在创建Update()方法所属的类的实例之后,您应该能够调用Update()方法。由于您没有提供完整的类定义,因此在下面的示例中,我将其称为MyClass

protected void btnYes_Click(object sender, EventArgs e)
{
    var myClass = new MyClass();
    myClass.Update(new clsRoom
    {
        RoomNo = 1234,
        Occupied = true
    });
}

话虽如此,作为主题外的话题,您的clsDataConnection类需要大量工作。我没看很久,但是让我惊讶的是,没有实现IDisposable的类(例如SqlConnectionSqlCommand等)被包裹在{{ 3}}阻止或调用using

我还注意到,该类对所有查询使用SqlConnection的共享实例。最佳做法是Dispose()

我还将反转您的某些if语句,并使用return摆脱一些不必要的else块。这样做的原因是为了减少不必要的嵌套并避免使用create one instance of SqlConnection per query / Pyramid of Doom

答案 1 :(得分:0)

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class news : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { 

    }
    protected void btnYes_Click(object sender, EventArgs e)
    {
        try
        {

            string str = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            SqlConnection con = new SqlConnection(str );
            SqlCommand cmd = new SqlCommand("sproc_tblRooms_Update", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@RoomNo", SqlDbType.VarChar).Value = txttitle.Text);
            cmd.Parameters.Add("@Occupied ", SqlDbType.VarChar).Value = Occupied.SelectedValue.ToString();
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            lblmsg.Text = "Room has been Updated Successfully";
        }
        catch (Exception)
        { }
    }
}