使用foreach和多个插入行?

时间:2014-10-10 15:15:46

标签: c# ms-access

我是来自C#的新手,我目前正在使用C#vs 2013和MS访问数据库..我正在尝试进行多个插入,同时尝试尝试foreach .. 我有2个访问表

第一张表

EID  ------ FirstName
10175-- random names
10176-- random names
10177-- random names
10178 --random names
10179 --random names
10180 --random names

第二张表

index--- EID-----Date(index is autonumber type)
1-------10175----10/10/2014
2-------10175----10/11/2014
3-------10175----10/12/2014
4-------10175----10/13/2014
5-------10175----10/14/2014
6-------10175----10/15/2014
7-------10175----10/16/2014
8-------10175----10/17/2014
9-------10175----10/18/2014
10------10175----10/10/2014

我想要发生的是当我点击一个按钮时,我想在第一张桌子上的第二张桌子上插入10个记录日期FOR EACH EID ...这是我的代码为10175的循环10记录

        connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        int ctr = 0;
        int counter;
        counter = int.Parse(TimeIntxt.Text);//I just use textbox for test i want this to be autogenerate based on the number of EID on first table 
        String counter2;
        for (ctr = 0; ctr < 10; ctr++)
        {
            counter++;
            counter2 = dateTimePicker1.Value.AddDays(ctr + 1).ToString();

            command10.CommandText = "insert into EmployeeData (EID,DateIn) values('" + counter + "','" + counter2 + "')";
            command10.ExecuteNonQuery();
        }

        MessageBox.Show("successfully created");
        connection.Close();


非常感谢能帮助我的人......如果我的英语不是很流利,我很抱歉Y.Y

1 个答案:

答案 0 :(得分:2)

connection.Open()
OleDBCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT EID From Table";

using (OleDbDataReader dr = command.ExecuteReader())
{
    while (dr.read())
    {
        //new connection
        for(var i = 0;i < 10;i++)
        {  
            //insert (int)dr["EID"] into 2nd table
        }

    }
}