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

后端 未结 2 373
情书的邮戳
情书的邮戳 2021-01-24 17:08

Objective: Using C# and SQL2008 correctly setup a Parameterized SQL Insert statement

Issue: The following statement is used in a for lo

相关标签:
2条回答
  • 2021-01-24 17:29

    struct is a keyword, you can't use it as a type name. 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.

    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);
    }
    
    0 讨论(0)
  • 2021-01-24 17:38

    You don't have to re-declare the variable inside the SQL code. This should work:

    sql =
        "INSERT INTO " +
            "database.dbo.table" +
                "(database.dbo.tabe.RowName) " +
        "VALUES " +
            "(@RowName) ";
    
    cmd.CommandText = sql;
    cmd.Parameters.AddWithValue("@RowValue ", Row.RowName);
    
    0 讨论(0)
提交回复
热议问题