在C#中形成参数化SQL语句的正确方法是什么

时间:2013-09-19 16:48:22

标签: c# sql parameterized-query

目标:使用C#和SQL2008正确设置参数化SQL插入语句

问题:在for循环中使用以下语句,因此必须清除这些值。运行此代码后,它表示语法错误接近250.代码如下

for (int i = 0; i < Rows.Count; i++)
{
    cmd.Parameters.Clear();

    struct Row = (struct)Rows[i];

    sql = "@RowName varchar(250) = null " +
    "INSERT INTO " +
        "database.dbo.table" +
             "(database.dbo.tabe.RowName) " +
    "VALUES " +
        "(@RowName) ";

 cmd.CommandText = sql;
 cmd.Parameters.AddWithValue("@RowValue ", Row.RowName);

}

提前感谢您提供更正,意见和建议。

2 个答案:

答案 0 :(得分:2)

您不必在SQL代码中重新声明变量。这应该有效:

sql =
    "INSERT INTO " +
        "database.dbo.table" +
            "(database.dbo.tabe.RowName) " +
    "VALUES " +
        "(@RowName) ";

cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@RowValue ", Row.RowName);

答案 1 :(得分:2)

struct是关键字,您不能将其用作类型名称。您不需要首先声明参数,(在这种情况下,从AddWithValue推断出所有必需的元数据),并且SQL查询中的参数名称必须与您在AddWithValue中放置的内容相匹配。

for (int i = 0; i < Rows.Count; i++)
{
    cmd.Parameters.Clear();

    var Row = (MyStruct)Rows[i];

    sql = "INSERT INTO " +
        "database.dbo.table " +
             "(database.dbo.tabe.RowName) " +
    "VALUES " +
        "(@RowName)";

    cmd.CommandText = sql;
    cmd.Parameters.AddWithValue("@RowName", Row.RowName);
}