带字符串的未处理格式异常

时间:2016-09-19 06:38:38

标签: c# string

以下代码用于更新数据库中的值

          string updateCom = ("UPDATE Login SET Username = '" + textUsername.Text + "', Password = '" + textPassword.Text + "', Role = '" + comboBox1.Text + "', First_Name = '" + char.Parse(textFirstName.Text) + "', Last_Name = '" + char.Parse(textLastName.Text) + "', Age = " + int.Parse(textAge.Text) + "', Gender = " + char.Parse(textAge.Text) + " WHERE User_ID = " + textUser_ID.Text);

整个事情都包含在try catch方法中,经过调试后我得到了

  

“FormatException未处理”

,它还说字符串必须只有一个字符长。这个未处理的异常仅在我输入“John Harambe”作为名字时才会发生。任何人都可以用正确的格式启发我吗?

我对我的问题的解决方案:

所以我按照其中一位评论者的建议使用了参数化查询,这是我到目前为止的代码;

       updateCom = new SqlCommand("UPDATE Login"
            + "SET Username = @username,"
            + "Password = @password,"
            + "Role = @role,"
            + "First_Name = @firstName,"
            + "Last_Name = @lastName,"
            + "Age = @age,"
            + "Gender = @gender"
            + "WHERE User_ID = @user_ID");

        updateCom.Connection = searchCon;
        searchCon.Open();

        String Username = textUsername.Text;
        String Password = textPassword.Text;
        String Role = comboBox1.Text;
        String First_Name = textFirstName.Text;
        String Last_Name = textLastName.Text;
        String Age = textAge.Text;
        String Gender = textGender.Text;

        if (searchCon.State == ConnectionState.Open)
        {
            updateCom.Parameters.AddWithValue("@username", Username);
            updateCom.Parameters.AddWithValue("@password", Password);
            updateCom.Parameters.AddWithValue("@role", Role);
            updateCom.Parameters.AddWithValue("@firstName", First_Name);
            updateCom.Parameters.AddWithValue("@lastName", Last_Name);
            updateCom.Parameters.AddWithValue("@age", Age);
            updateCom.Parameters.AddWithValue("@gender", Gender);

            try
            {
                updateCom.ExecuteNonQuery();
                if (MessageBox.Show("Data UPDATED.", "Admin Power",
                    MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    searchCon.Close();
                }
                else
                {
                    if(MessageBox.Show("Data NOT UPDATED", "Admin Power",
                        MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                searchCon.Close();
            }
        }

它仍然会抛出未处理的异常

  

“'用户名'附近的错误语法。”

1 个答案:

答案 0 :(得分:1)

Errr,char.parse需要一个单字符串。

char.Parse

所以,当然,如果你的名字或姓氏字符串更长,你就会得到那个例外......