在C#中形成参数化SQL语句的正确方法是什么 [英] What is the correct way to form a parameterized SQL statement in C#

查看:394
本文介绍了在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);

这篇关于在C#中形成参数化SQL语句的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆