在sql数据库中插入可能超出范围

时间:2017-01-06 13:48:38

标签: mysql list keyvaluepair indexoutofrangeexception

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

[
    'username' => 'John Doe',
    'mail' => 'john@example.org',
    'password' => 'whatever',
    'photo' => [
        'name' => 'myImage.jpg',
        'type' => 'image/jpeg',
        'tmp_name' => '/private/var/tmp/phpN3dVmL',
        'error' => (int) 0,
        'size' => (int) 40171
    ]
]

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

1 个答案:

答案 0 :(得分: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)
        });
}

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