Let me show you a complete example.
First, you always need to use parameters. This will protect against sql injections and speed up the execution of queries.
Secondly, it is always necessary to release the occupied resources, therefore we use the using construction.
Thirdly, we observe the generally accepted naming.
It is given: the filled list
List<string> samples = new List<string>();
Code:
using (var conn = new SqlConnection(connectionString)) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT * FROM table WHERE c1 = @param"; ; var sqlParameter = cmd.Parameters.Add("param", SqlDbType.NVarChar); foreach (var sample in samples) { sqlParameter.Value = sample; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { // здесь получаем значения из ридера } } } } }
You did not specify which DBMS you are using. The example assumes Sql Server. If another is used, replace, respectively, SqlConnection and SqlDbType with the desired types.
SELECT * FROM db WHERE c1 in (1,3,5)and the list can be formed like this:List<string> Sample = new List<string>() { "1", "3", "5" }; var result = String.Join(", ", names.ToArray());List<string> Sample = new List<string>() { "1", "3", "5" }; var result = String.Join(", ", names.ToArray());- virex-84foreach(String item in Sample) { }for(int i = 0; i < Sample.Count; i++) { }- virex-84