正确的where in 语句参数化写法

  相信大家对SQL中的参数化查询并不陌生吧?可是有时候我总是记不住where in 语句的参数化查询方法该怎么写。于是写在这里给自己做个备忘,顺便也提醒一下和我有一样毛病的朋友。

  

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data;
 4 using System.Data.Common;
 5 using System.Data.SqlClient;
 6 using System.Linq;
 7 using System.Runtime.Remoting.Messaging;
 8 using System.Security.AccessControl;
 9 using System.Text;
10 
11 namespace ConsoleApplication5
12 {
13     class Program
14     {
15         static void Main(string[] args)
16         {
17             //记得替换成你自己的数据库连接字符串
18             string connection = "Data Source=(Local);Initial Catalog=;Persist Security Info=True;User ID=sa;PassWord=";
19             SqlConnection conn = new SqlConnection(connection);
20             conn.Open();
21             List<int> lst = new List<int>(){1,3,5};
22             List<SqlParameter> lstPara = new List<SqlParameter>();
23             //组合参数查询需要的where in 语句
24             string cmd = "(";
25             for (int i = 0; i < lst.Count(); i++)
26             {
27                 //将参数名添加到字符串中
28                 cmd += "@ID" + (i+1)+",";
29                 //将参数添加到SqlParameter列表中
30                 lstPara.Add(new SqlParameter("@ID"+(i+1),lst[i]));
31             }
32             //最后要保证参数字符串是这种形式:(@para1,@para2,@para3,.....)
33             cmd = cmd.Remove(cmd.Length - 1);
34             cmd += ")";
35             
36             SqlCommand command = new SqlCommand("select * from T_Code_Children where vCodeID in"+cmd,conn);
37             command.Parameters.AddRange(lstPara.ToArray());
38             DataTable dt = new DataTable();
39             SqlDataAdapter adapter = new SqlDataAdapter(command);
40             adapter.Fill(dt);
41             //在这里下个断点 看一下是否执行成功
42             conn.Close();
43             Console.ReadLine();
44 
45         }
46     }
47 }

  顺便说一下,where in(@para) ; @para ="value1,value2,value3,value4....."

  以及

  where in @para ;@para ="(value1,value2,value3,value4......)"

  这两种形式都是行不通的哦。SQL将每个参数作为一个值使用,而不是单纯的作为字符串和Command拼在一起。

posted @ 2015-02-08 14:02  仙贝  阅读(2138)  评论(0)    收藏  举报