简体   繁体   English

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

[英]What is the correct way to form a parameterized SQL statement in C#

Objective: Using C# and SQL2008 correctly setup a Parameterized SQL Insert statement 目标:使用C#和SQL2008正确设置参数化SQL插入语句

Issue: The following statement is used in a for loop so the values must be cleared. 问题:在for循环中使用以下语句,因此必须清除值。 Upon running this code it states there is a syntax error near 250. The code is as follows 在运行此代码时,它指出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);

} }

Thank you in advance for corrections, comments and suggestions. 提前感谢您的更正,意见和建议。

You don't have to re-declare the variable inside the SQL code. 您不必在SQL代码中重新声明该变量。 This should work: 这应该工作:

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

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

struct is a keyword, you can't use it as a type name. struct是一个关键字,您不能将其用作类型名称。 You don't need to declare the parameter first, (all necessary metadata is inferred from AddWithValue in this case) and the parameter name in the SQL query has to match what you put in AddWithValue . 您不需要首先声明参数(在这种情况下,从AddWithValue推断出所有必需的元数据),并且SQL查询中的参数名称必须与您在AddWithValue放置的内容相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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM