【问题标题】:How to pass variable into SqlCommand statement and insert into database table如何将变量传递给 SqlCommand 语句并插入数据库表
【发布时间】:2011-05-02 16:40:55
【问题描述】:

我正在用 C# 编写一个小程序,它使用 SQL 在运行时根据用户的输入将值存储到数据库中。

唯一的问题是我无法找出正确的 Sql 语法来将变量传递到我的数据库中。

private void button1_Click(object sender, EventArgs e)
    {
        int num = 2;

        using (SqlCeConnection c = new SqlCeConnection(
            Properties.Settings.Default.rentalDataConnectionString))
        {
            c.Open();
            string insertString = @"insert into Buildings(name, street, city, state, zip, numUnits) values('name', 'street', 'city', 'state', @num, 332323)";
            SqlCeCommand cmd = new SqlCeCommand(insertString, c);
            cmd.ExecuteNonQuery();
            c.Close();
        }

        this.DialogResult = DialogResult.OK;
    }

在这段代码 sn-p 中,我使用了所有静态值,除了我试图传递给数据库的 num 变量。

在运行时我收到此错误:

A parameter is missing. [ Parameter ordinal = 1 ]

谢谢

【问题讨论】:

    标签: c# sql sqlcommand executenonquery


    【解决方案1】:

    在命令执行前添加参数:

    cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;
    

    【讨论】:

    • 这正是我所需要的。感谢您的快速回复。
    【解决方案2】:

    您没有在 SQL 语句中为 @ 参数提供值。 @ 符号表示一种占位符,您将在其中传递值。

    使用this example 中的SqlParameter 对象将值传递给该占位符/参数。

    有很多方法可以构建参数对象(不同的重载)。如果您遵循相同的示例,一种方法是在声明命令对象的位置之后粘贴以下代码:

            // Define a parameter object and its attributes.
            var numParam = new SqlParameter();
            numParam.ParameterName = " @num";
            numParam.SqlDbType = SqlDbType.Int;
            numParam.Value = num; //   <<< THIS IS WHERE YOUR NUMERIC VALUE GOES. 
    
            // Provide the parameter object to your command to use:
            cmd.Parameters.Add( numParam );
    

    【讨论】:

      猜你喜欢
      • 2012-04-20
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 2014-06-14
      • 1970-01-01
      • 2012-10-31
      相关资源
      最近更新 更多