【问题标题】:using foreach and multiple insert rows?使用 foreach 和多个插入行?
【发布时间】:2023-03-15 04:44:01
【问题描述】:

我是 C# 的新手,我目前正在使用 C# vs 2013 和 MS access 数据库..我正在尝试进行多次插入,同时尝试尝试 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

我想要发生的事情是,当我单击一个按钮时,我想在第一个表上的每个 EID 的第二个表上插入 10 个记录日期。这是我为 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

【问题讨论】:

  • 听起来你会想要使用OleDbDataReader 来循环第一个表中的行。有关示例,请参阅相关问题 here

标签: c# ms-access


【解决方案1】:
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
        }

    }
}

【讨论】:

  • 为什么你提供的代码中的 SqlDataReader 仍然在下面的红线上我知道这意味着我错过了那里的错误?
  • 试图用 OleDbDataReader 改变 SqlDataReader 并且这次 dr.read() 变红了
  • 顺便问一下如何使用block?
  • 您确实需要查看 OleDbDataReader 对象的文档并找到要使用的适当方法。我实际上只是给你一个关于如何构造你的代码来完成你想要的东西的大致想法,而不是为你编写代码。
猜你喜欢
  • 2019-07-15
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 2023-03-13
  • 2010-12-21
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
相关资源
最近更新 更多