【问题标题】:Inserting in sql Database while maybe out of range在可能超出范围时插入 sql 数据库
【发布时间】:2017-01-06 22:00:02
【问题描述】:

我有一个问题。我正在尝试将一些值插入到 mySql 数据库中,但我遇到了一个小问题。

        for (int i = 0; i < Chauffeurlijst.Count; i++)
        {
            db.Insert("Insert into route (Voertuigen_ID,Chauffeurs_ID,Planning_ID) VALUES(@voertuigid,@chauffeurid,@planningid", new List<KeyValuePair<string, object>>
        {

            new KeyValuePair<string, object>("@voertuigid", Voertuigenlijst[i].ID),
            new KeyValuePair<string, object>("@chauffeurid", Chauffeurlijst[i].ID),
            new KeyValuePair<string, object>("@planningid", planning.ID)
        });
        }

我有两个值得注意的变量:一个 voertuigenlijst(一个 voertuig 列表)和一个 chauffeurlijst(一个司机列表) 但问题是 Voertuigenlijst 的计数可能小于 Chauffeurlijst 的计数。它也可能是一样的。当 chauffeurlijst 较小时,程序当然会崩溃,因为 voertuigen 列表中的最后一项已被分配。我想做的是当 voertuigenlijst[i] 不再存在时,我想做 i-1。这个问题有好的解决方案吗?

【问题讨论】:

  • 为什么不在循环中检查 i 并执行您想要的操作
  • 因为在我的数据库中,我保留了所有司机驾驶一条路线
  • 这甚至没有意义,您必须检查 i 是否大于您的 Chauffeurlijst.count 并且它与您的数据库无关

标签: mysql list keyvaluepair indexoutofrangeexception


【解决方案1】:

您可以通过使用另一个局部变量来确定 Voertuigenlijst 的索引来执行此操作。基本上,您要检查索引是否在您的范围内。如果没有,则使用列表中的最后一个索引。例如——

for (int i = 0; i < Chauffeurlijst.Count; i++)
{
    var j = i < Voertuigenlijst.Count ? i : Voertuigenlijst.Count - 1;
    db.Insert("Insert into route (Voertuigen_ID,Chauffeurs_ID,Planning_ID) VALUES(@voertuigid,@chauffeurid,@planningid",
        new List<KeyValuePair<string, object>>
        {
            new KeyValuePair<string, object>("@voertuigid", Voertuigenlijst[j].ID),
            new KeyValuePair<string, object>("@chauffeurid", Chauffeurlijst[i].ID),
            new KeyValuePair<string, object>("@planningid", planning.ID)
        });
}

如果Chauffeurlijst.Count > Voertuigenlijst.Count,这将使用列表中的最后一个Voertuig。但是,此代码不处理 Voertuigenlijst.Count > Chauffeurlijst.Count 的情况。我相信你可以使用这个例子找到一个好的解决方案。您可能还想处理一个为空的情况。

【讨论】:

  • 嗨,汤姆,感谢您的回答并与我一起思考。答案确实正是我所需要的。 Voertuigenlijst.count > Chauffeurlijst.Count 是不可能的。而且其中一个也不可能为空,因为在此之前检查了两个变量。
  • 太棒了!没问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 2016-01-09
  • 2018-09-19
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
相关资源
最近更新 更多