C#for循环问题,返回

时间:2016-08-25 12:48:01

标签: c# for-loop

我有一个代码,我想运行100次。我做的是一个for循环,但我得到一个异常(必须在MySQL的字段中输入NOT重复值)重复,所以我想我做错了。我认为for不会向前发展。我做错了什么?

//loop for each user
for (int loop_counter = 1; loop_counter <= 100; loop_counter++)
{
    if (loop_counter < 10)
    {
        userid_value = company_value + "00" + loop_counter;
        username_value = company_value +"00" + loop_counter;
    }
    else
    {
        userid_value = company_value + "0" + loop_counter;
        username_value = company_value + "0" + loop_counter;
    }
    if (loop_counter == 100)
    {
        // Final Value of Label when all added
        Result_Label_Reply.Content = "100 Users added to" + company_value + ". Success.";
    }
    //radioButton Check to proceed
    if (Validation_Yes.IsChecked.Value && loop_counter < 100)
    {
        int companyId = dbm.FindCompanyId(company_value);
        if (dbm.AddUser(userid_value, username_value, pass, companyId))
        {
            Result_Label_Reply.Content = "User " + username_value + "added to" + company_value + " Successfully.";
            Validation_Yes.IsChecked = false;
            Company_Value_TextBox.Text = "";

        }
        else
        {
            Result_Label_Reply.Content = "Mysql exception ERROR.";
            Validation_Yes.IsChecked = false;
        }

    }

    else
    {
        Result_Label_Reply.Content = "Something went wrong, please try again.";

    }
}

编辑:这是我收到的异常,这意味着该函数尝试两次输入第一个用户名的值。我有一家名为Star的公司,所以它试图把Star001放在一边但是没有意义,因为它说它有一个公开的条目

注意:它只添加第一个用户。

Activated   Event   Time    Duration    Thread
Exception: Exception thrown: 'MySql.Data.MySqlClient.MySqlException' in MySql.Data.dll ("Duplicate entry 'Star001' for key 'name'"). Exception thrown: 'MySql.Data.MySqlClient.MySqlException' in MySql.Data.dll ("Duplicate entry 'Star001' for key 'name'")   22.34s      [12128] <No Name> 

编辑2:我提供了AddUser的代码,但我认为问题不存在,因为第一个用户已成功添加到数据库中。

public bool AddUser(string userid, string username, string password, int companyId)
{
    return ExecQuery("insert into users (id, name, pass, companyid) values (@id, @name, @pass, @cid)", 
    cmd =>
        {
            cmd.Parameters.AddWithValue("@id", userid);
            cmd.Parameters.AddWithValue("@name", username);
            cmd.Parameters.AddWithValue("@pass", password);
            cmd.Parameters.AddWithValue("@cid", companyId);
            return cmd;
        });
}

0 个答案:

没有答案