1

当我按下按钮时,我的 C# 代码中出现以下错误。它被我的 try-catch 捕获:

MySql.Data.dll 中发生了“MySql.Data.MySqlClient.MySqlException”类型的第一次机会异常

我想知道这可能是什么问题。任何帮助表示赞赏!

方法:

private void addChildBtn_Click(object sender, EventArgs e)
{
    string firstName = firstNameAdd.Text;
    int ageComboIndex = ageComboAdd.SelectedIndex;
    string age = this.ageComboAdd.Items[ageComboIndex].ToString();

    int genderComboIndex = genderComboAdd.SelectedIndex;
    string gender = this.genderComboAdd.Items[genderComboIndex].ToString();

    string address = addressAdd.Text;

    string caregiverOneName = caregiver1NameAdd.Text;
    string caregiverOnePhone = caregiver1PhoneAdd.Text;
    string caregiverTwoName = caregiver2NameAdd.Text;
    string caregiverTwoPhone = caregiver2PhoneAdd.Text;

    server = "localhost";
    port = "3306";
    database = "childeren";
    uid = "root";
    password = "password";

    MySqlConnection connection2 = new MySqlConnection("Server=" + server + ";" + 
        "Port=" + port + ";" + "Database=" + database + ";" + 
        "Uid=" + uid + ";" + "Password=" + password + ";");

    // Perform databse operations
    try
    {
        connection2.Open();
        string query = "INSERT INTO childdatabase (name2, age, gender, " +
            "adress, caregiver1Name, caregiver1Phone, caregiver2Name, " +      
            "caregiver2Phone) VALUES('" + firstName + "','" + age + 
            "','" + gender + "','" + address + "','" + caregiverOneName + 
            "','" + caregiverOnePhone + "','" + caregiverTwoName + 
            "','" + caregiverTwoPhone + "')";
        MySqlCommand cmd = new MySqlCommand(query, connection2);

        cmd.ExecuteNonQuery();
        connection2.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show("Failed");
        //updateStatus(ex.Message.ToString());
    }

    connection2.Close();
}

MySQL CREATE 表设置:

create database childeren;
use childeren;
CREATE TABLE childDatabase 
(
    id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    name2 VARCHAR(50), 
    age VARCHAR(3), 
    gender VARCHAR(6), 
    adress VARCHAR(50), 
    caregiver1Name VARCHAR(50), 
    caregiver1Phone VARCHAR(10), 
    caregiver2Name VARCHAR(50), 
    caregiver2Phone VARCHAR(10)
);
4

1 回答 1

0

您在查询字符串中忘记了一个(双)引号?具体之前caregiver2Phone

string query = "INSERT INTO childdatabase (name2, age, gender, " +
        "adress, caregiver1Name, caregiver1Phone, caregiver2Name, " +      
        "caregiver2Phone) VALUES('" + firstName + "','" + age + 
        "','" + gender + "','" + address + "','" + caregiverOneName + 
        "','" + caregiverOnePhone + "','" + caregiverTwoName + 
        "','" + caregiverTwoPhone + "')";
于 2013-06-24T03:30:04.140 回答