无法从C#更新SQL数据库

时间:2014-12-22 07:52:49

标签: c# sql-server winforms stored-procedures

我无法通过存储过程更新SQL数据库中的字段。 以下是c#代码。我在存储过程和c#代码中都没有语法错误或任何内容。

private void btnUpdate_Click(object sender, EventArgs e)
{
   try
   {
        SqlCommand commandp = new SqlCommand("spUpdateCmpStructure", dbcon.con);
        commandp.CommandType = CommandType.StoredProcedure;
        commandp.Parameters.AddWithValue("@cmpID", txtCmp.Text.ToString());
        commandp.Parameters.AddWithValue("@cmpName", txtCmp.Text.ToString());
        commandp.Parameters.AddWithValue("@cmpDesc", txtDetails.Text.ToString());
        commandp.Parameters.AddWithValue("@cmpAddress", txtAddress.Text.ToString());
        commandp.Parameters.AddWithValue("@cmpType", cbType.Text.ToString());
        commandp.Parameters.AddWithValue("@cmpParent", cbParent.Text.ToString());

        dbcon.openConnection();

        int check = commandp.ExecuteNonQuery();

        if (check > 0)
        {
            MessageBox.Show(txtCmp.Text.ToString() + " Updated");
        }
        else
        {
            MessageBox.Show(txtCmp.Text.ToString() + " Update Failed");
        }

        dbcon.closeConnection();
        }
        catch (Exception ex)
        {
             MessageBox.Show(ex.Message);
         }
         finally 
         {
             dbcon.closeConnection();
         }

以下是存储过程

USE [xxx]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Spupdatecmpstructure] @cmpID      VARCHAR(10),
                                             @cmpName    VARCHAR(50),
                                             @cmpDesc    VARCHAR(100),
                                             @cmpAddress VARCHAR(50),
                                             @cmpType    VARCHAR(20),
                                             @cmpParent  VARCHAR(50)
AS
  BEGIN
      UPDATE cmpStructure
      SET    cmpName = @cmpName,
             cmpDesc = @cmpDesc,
             cmpAddress = @cmpAddress,
             cmpType = @cmpType,
             cmpParent = @cmpParent
      WHERE  cmpID = @cmpID
  END 

1 个答案:

答案 0 :(得分:0)

在此您可以看到,id和name字段的边界值相同 txtCmp.Text.ToString()

commandp.Parameters.AddWithValue("@cmpID", txtCmp.Text.ToString());
commandp.Parameters.AddWithValue("@cmpName", txtCmp.Text.ToString());