参数化查询需要参数' @ Id',这是未提供的

时间:2016-11-14 10:12:28

标签: c# sql-server stored-procedures ado.net

我正在编写一个使用方法(parameters.add)的软件,但是当我向数据库添加数据时,我得到以下错误:

  

参数化查询需要参数' @ Id',而不是   提供。

我看到了几个主题,但我无法解决我的问题。

The parameterized query expects the parameter ###### which was not supplied

The parameterized query expects the parameter , which was not supplied

我在下面放了c#代码和存储过程代码:

private void btnSave_Click(object sender, EventArgs e)
        {
            string cs = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TranscactionAccountNumber;Data Source=DESKTOP-5DJFFQP";
            string name = txtName.Text;
            int shomarepeygiri = int.Parse(txtShomarePeygiri.Text);
            string date = dtpDate.Shamsi;
            decimal mablagh = decimal.Parse(txtMablagh.Text);
            string comment = txtComment.Text;
            using (cn = new SqlConnection(cs))
            using (cmd = new SqlCommand("InsertTransaction", cn))
            {
                cmd.Parameters.Add("@Id",SqlDbType.Int);
                cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 100).Value = name;
                cmd.Parameters.Add("@ShomarePeygiri", SqlDbType.Int).Value = shomarepeygiri;
                cmd.Parameters.Add("@Mablagh", SqlDbType.Decimal).Value = mablagh;
                cmd.Parameters.Add("@Comment", SqlDbType.NVarChar).Value = comment;
                cmd.Parameters.Add("@Date", SqlDbType.VarChar).Value = date;
                if (cn.State == ConnectionState.Closed)
                    cn.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Transaction Added Successfully..", "Register Transaction", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }


        }
Create procedure InsertTransaction
(
@id int,
@Name nvarchar(100),
@ShomarePeygiri int,
@Mablagh decimal(18, 0),
@Comment nvarchar(MAX),
@PersianDate varchar(10)

) 
AS
Insert Into TransactionTable(id,[Name],ShomarePeygiri,Mablagh,Comment,PersianDate)
 values (@id,@Name,@ShomarePeygiri,@Mablagh,@Comment,@PersianDate)

2 个答案:

答案 0 :(得分:6)

cmd.Parameters.Add("@Id",SqlDbType.Int);

您正在添加参数,但您没有为其提供值。因此,您收到此错误。

如果ID列是自动增量,只需将其从存储过程中删除。

编辑:如果您不知道如何创建自动递增的列,请检查以下答案: 的 Auto increment primary key in SQL Server Management Studio 2012

答案 1 :(得分:2)

改变您的程序如下

Alter procedure InsertTransaction
(
@Name nvarchar(100),
@ShomarePeygiri int,
@Mablagh decimal(18, 0),
@Comment nvarchar(MAX),
@PersianDate varchar(10)
) 
AS
Insert Into TransactionTable([Name],ShomarePeygiri,Mablagh,Comment,PersianDate)
values (@Name,@ShomarePeygiri,@Mablagh,@Comment,@PersianDate)