ASP C#|使用SQL和存储过程更新数据库

时间:2010-12-15 23:47:00

标签: c# sql stored-procedures

这是我的OnClick事件:

protected void Submit_Click(object sender, EventArgs e)
{
    try
    {
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand("administratorUpdate", con))
            {
                cmd.Parameters.Add("@originalID", SqlDbType.VarChar).Value = IDHF.Value;
                cmd.Parameters.Add("@firstName", SqlDbType.VarChar).Value = firstNameTB.Text;
                cmd.Parameters.Add("@lastName", SqlDbType.VarChar).Value = lastNameTB.Text;
                cmd.Parameters.Add("@userName", SqlDbType.VarChar).Value = userNameTB.Text;
                cmd.Parameters.Add("@emailAddress", SqlDbType.VarChar).Value = emailAddressTB.Text;
                cmd.CommandType = CommandType.StoredProcedure;
            }
        }
        GetAllRPT.DataBind();
        Label ErrorMessageLabel = (Label)Master.FindControl("ErrorMessageLabel");
        new myFunctions().DisplayUserMessage("success", "Administrator Updated!", ErrorMessageLabel);
        AdminForm.Visible = false;
    }
    catch (Exception ex)
    {
        Label ErrorMessageLabel = (Label)Master.FindControl("ErrorMessageLabel");
        new myFunctions().DisplayUserMessage("error", ex.Message, ErrorMessageLabel);
    }
}

这是我的存储过程[administratorUpdate]:

ALTER PROCEDURE [dbo].[administratorUpdate]
    @originalID UNIQUEIDENTIFIER,
    @firstName varchar (100),
    @lastName varchar (100),
    @userName varchar (100),
    @emailAddress varchar (100),
    @password varchar (100),
    @isActive bit
AS

UPDATE administrator
SET userName = @userName,
    emailAddress = @emailAddress,
    password = @password,
    firstName = @firstName,
    lastName = @lastName,
    isActive = @isActive
WHERE
    ID = @originalID

代码执行并执行成功消息,但数据表不会更新。谁知道为什么?我不熟悉在ASP中使用存储过程。

2 个答案:

答案 0 :(得分:5)

你在执行命令吗?

    using (SqlConnection con = new SqlConnection(conString))
    {
        conn.Open(); //this was missing

        using (SqlCommand cmd = new SqlCommand("administratorUpdate", con))
        {
            cmd.Parameters.Add("@originalID", SqlDbType.VarChar).Value = IDHF.Value;
            cmd.Parameters.Add("@firstName", SqlDbType.VarChar).Value = firstNameTB.Text;
            cmd.Parameters.Add("@lastName", SqlDbType.VarChar).Value = lastNameTB.Text;
            cmd.Parameters.Add("@userName", SqlDbType.VarChar).Value = userNameTB.Text;
            cmd.Parameters.Add("@emailAddress", SqlDbType.VarChar).Value = emailAddressTB.Text;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery(); //this was missing.
        }

        conn.Close();
    }

答案 1 :(得分:1)

我的诀窍是在调试模式下执行此操作而不使用Try / Catch。生成的错误将指向问题。