MySQL 使用参数重构查询后的连接问题

MySQL connection issue after refactor query with parameters

我正在尝试使用参数化查询重构我的代码。

该代码试图根据两个文本框 - student_lastname 和 student_name 将数据插入 MySQL 数据库。但似乎我在连接中犯了某种错误。

下面是我的尝试:

static string conString = ConfigurationManager.ConnectionStrings["SchoolGrades.Properties.Settings.ConnectionString"].ConnectionString;
DataTable dt = new DataTable();

private void btnNew_Click(object sender, EventArgs e)
{

    string sqlCommand = 
        "INSERT INTO OceniStudents(student_name, student_lastname) + " +
                           "VALUES(?student_name, ?student_lastname);";

    try
    {
        using (MySqlConnection con = new MySqlConnection(conString))
        {
            MySqlCommand cmdDatabase = new MySqlCommand(sqlCommand, con);
            cmdDatabase.Prepare();
            cmdDatabase.Parameters.Add(new MySqlParameter("student_name", this.txtStudentName));
            cmdDatabase.Parameters.Add(new MySqlParameter("student_lastname", this.txtStudentLastName));

            MySqlDataReader myReader;
            myReader = cmdDatabase.ExecuteReader();

            MessageBox.Show("Data is inserted.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

但是一旦我调用方法 - btnNew_Click - 我得到一个错误:The connection is not open

我已经仔细检查过 - 连接字符串、服务器、数据库 table 都已设置。

知道我错过了什么吗?

您的代码中缺少 con.Open();

try { using (MySqlConnection con = new MySqlConnection(conString)) { con.Open(); MySqlCommand cmdDatabase = new MySqlCommand(sqlCommand, con); cmdDatabase.Prepare(); cmdDatabase.Parameters.Add(new MySqlParameter("student_name", this.txtStudentName)); cmdDatabase.Parameters.Add(new MySqlParameter("student_lastname", this.txtStudentLastName)); MySqlDataReader myReader; myReader = cmdDatabase.ExecuteReader(); MessageBox.Show("Data is inserted.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information); } }

创建连接对象后,您应该使用 Open 函数打开连接。

....
using (MySqlConnection con = new MySqlConnection(conString))
{
    con.Open();
    ....
}