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

若如初见. 提交于 2019-12-02 06:35:36

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);

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!