在C#中形成参数化SQL语句的正确方法是什么
问题描述:
目标:使用C#和SQL2008正确设置参数化的SQL插入语句
Objective: Using C# and SQL2008 correctly setup a Parameterized SQL Insert statement
问题:在for循环中使用以下语句,因此必须清除这些值.运行此代码后,它指出在250附近存在语法错误.代码如下
Issue: The following statement is used in a for loop so the values must be cleared. Upon running this code it states there is a syntax error near 250. The code is as follows
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.
答
您不必在SQL代码中重新声明变量.这应该起作用:
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);