循环通过数组向sql查询添加参数

时间:2013-05-06 23:58:14

标签: c# arrays foreach windows-applications

我正在从文本文件中读取行并将它们存储到数组中。我现在需要循环遍历每个数组位置的项目。我可以遍历文档中的行,但我也需要循环遍历数组值。

以下是我阅读文本文件和构建数组的代码:

  public class people
    {
       public  string name;
       public int empid;
       public  string address;

     }

    private void read()
    {


        using (StreamReader sr = new StreamReader(@"E:\test.txt"))
        {
            while (sr.Peek() >= 0) << This loops through the rows in the text doc 
            {
                string str;
                string[] strArray;
                str = sr.ReadLine();

                strArray = str.Split(',');

                people new_people = new people();

                new_people.name = strArray[0];
                new_people.empid = int.Parse(strArray[1]); // << I need to be able to loop through each of
                new_people.address = strArray[2];          // these and add each on to my query string 
                peoples.Add(new_people);

                listBox1.Items.Add(new_people.name + new_people.empid + new_people.address); //< this displays 
                                                                        // the array values     

            }
          }

我需要这样的东西:

   foreach (string foo in new_people.name[0] )
            {

                cmd.Parameters.Add("@1", SqlDbType.VarChar).Value = foo ;

               // then do this for every item in the array for that position 

                cmd.Parameters.Add("@2", SqlDbType.VarChar).Value = (next set of values);
                cmd.Parameters.Add("@3", SqlDbType.VarChar).Value = (next set of values);

                cmd.ExecuteNonQuery();

            }

1 个答案:

答案 0 :(得分:0)

创建自己的构造函数将帮助您创建Person类的实例(人是单数,人是复数):

public class Person
{
    public string Name;
    public int Empid;
    public string Address;

    public Person(string name, int empid, string address)
    {
        Name = name;
        Empid = empid;
        Address = address;
    }
}

private void read()
{
    using (StreamReader sr = new StreamReader(@"E:\test.txt"))
    {
        while (sr.Peek() >= 0) 
        {
            string str;
            string[] strArray;
            str = sr.ReadLine();
            strArray = str.Split(',');

            Person newPerson = new Person(strArray[0], int.Parse(strArray[1]), strArray[2]);
            people.Add(newPerson);

            listBox1.Items.Add(newPerson.Name + newPerson.Empid + newPerson.Address);
        }
    }

然后你可以遍历所有名字:

int i = 0;
foreach (Person p in people)
    cmd.Parameters.Add("@" + (i++), SqlDbType.VarChar).Value = p.Name;
cmd.ExecuteNonQuery();