Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用多个参数运行SQL查询_C#_.net_Sql Server_Sql Injection - Fatal编程技术网

C# 使用多个参数运行SQL查询

C# 使用多个参数运行SQL查询,c#,.net,sql-server,sql-injection,C#,.net,Sql Server,Sql Injection,我知道为了防止SQL注入,您会使用像@param1和@param2这样的参数,但是当您需要多次传递相同的参数时,您如何实现这一点呢 现在,参数将从winform上的两个文本框中传入。但是我的朋友呢?C#如何处理将参数传递到sql字符串中的两个不同位置 ;WITH CTE AS ( Select RTRIM(LTRIM(employeename)) As employeename ,psrti ,nes FROM helper1

我知道为了防止SQL注入,您会使用像
@param1
@param2
这样的参数,但是当您需要多次传递相同的参数时,您如何实现这一点呢

现在,参数将从winform上的两个文本框中传入。但是我的朋友呢?C#如何处理将参数传递到sql字符串中的两个不同位置

;WITH CTE AS
(
       Select
       RTRIM(LTRIM(employeename)) As employeename
       ,psrti
       ,nes
       FROM helper1
)
Select 
[Employee Name] = RTRIM(LTRIM(cte.employeename))
,[days employed] = (Select COUNT([days]) 
                           FROM [empinfo] jb 
                           WHERE CAST([hiredate] As Date) BETWEEN @startdate AND @enddate 
                           AND RTRIM(LTRIM(jb.employeename)) = RTRIM(LTRIM(cte.employeename)))
,[terminated emps] = (Select Count(empID) from terminate where termination date between @startdate AND @enddate)
FROM hrfile  hr1
RIGHT JOIN CTE cte
ON hr1.employeename = cte.employeename
GROUP BY RTRIM(LTRIM(cte.employeename)),RTRIM(LTRIM(hr1.employeename)),cte.nes
ORDER BY RTRIM(LTRIM(cte.employeename)) ASC
我知道只要有第一套参数我就可以

string sql = "";;

using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
  var param1 = new SqlParameter("param1", SqlDbType.DateTime);
  var param2 = new SqlParameter("param2", SqlDbType.DateTime);
  param1.Value = txtOne.Text;
  param2.Value = txtTwo.Text;
  command.Parameters.Add(param1);
  command.Parameters.Add(param2);
  var results = command.ExecuteReader();
}

即使参数被多次使用,也可以执行相同的操作(仅设置一次参数值)。C#/ADO.NET将负责在多个位置用指定值替换参数。

只要SQL字符串格式正确,它将处理多次读取参数的操作。不过,我还是会转换成存储过程。@DaniDev-存储过程会比直接sql语句快吗?在我的测试实例中,直接sql语句的速度更快。原因有二:1。如果您的查询有点复杂,那么调试存储过程就容易多了。2.这样更安全