c# - 使用存储过程更新 C# 中的列

标签 c# asp.net sql-server stored-procedures sql-update

我正在尝试通过填写文本框并单击“保存”来更新表格中的列;我没有得到错误或任何东西。就是什么都没发生!

这是我的存储过程:

ALTER PROCEDURE [dbo].[sp_UpdateProj]
    @ORAID INT = NULL,
    @FullTitle NVARCHAR(250) = NULL
AS
BEGIN
    UPDATE tbl_ProjectFile
    SET FullTitle = @FullTitle
    WHERE ORAID = @ORAID
END

当我在 SQL Server Management Studio 中运行它时,给定一个 ID 和标题名称,它就可以工作

这是我的C#代码

protected void Button_Save_Click(object sender, EventArgs e)
{
    string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(connectionStr))
    {
        con.Open();

        string query = "sp_UpdateProj Where ORAID=" + int.Parse(TextBox_ORAID.Text);

        SqlCommand cmd = new SqlCommand(query, con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = con;

        cmd.Parameters.AddWithValue("@ORAID", Convert.ToInt32(TextBox_ORAID.Text));
        cmd.Parameters.AddWithValue("@FullTitle", TextBox_FullTitle.Text);

        con.Close();
    }
}

最佳答案

您(几乎)正确地设置了所有内容 - 但您从未实际执行存储过程!

试试这段代码:

protected void Button_Save_Click(object sender, EventArgs e)
{
    string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
    // the query string should be **ONLY** the stored procedure name - nothing else!
    string query = "dbo.sp_UpdateProj";

    // you should put **both** SqlConnection and SqlCommand in "using" blocks
    using (SqlConnection con = new SqlConnection(connectionStr))
    using (SqlCommand cmd = new SqlCommand(query, con))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        // fill the parameters - avoiding "AddWithValue"
        cmd.Parameters.Add("@ORAID", SqlDbType.Int).Value = Convert.ToInt32(TextBox_ORAID.Text);
        cmd.Parameters.Add("@FullTitle", SqlDbType.NVarChar, 250).Value = TextBox_FullTitle.Text;

        con.Open();
        // you need to **EXECUTE** the command !
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

关于c# - 使用存储过程更新 C# 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51678243/

相关文章:

c# - 实体到 WCF 数据协定

c# - Json反序列化和ADO持久化过程中的字符串截断

javascript - 更改 Javascript 中的 asp 变量?

sql-server - SQL Server 2008。允许远程连接吗?

c# - 如何使用 EF6 和 SQL Server 捕获 UniqueKey Violation 异常?

c# - WindowProc 对于 c# 中的窗体

c# - 如何重构重复的事件处理代码

c# - Task.Run 与 null SynchronizationContext

asp.net - 如何在 SQL Server 的 log4net 配置中使用存储过程进行日志记录

SQL Server 2008 错误 - 无法为对象分配空间