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

时间:2018-05-06 01:23:16

标签: c# mysql ado.net

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

代码试图根据两个文本框 - 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

我已经双重检查 - 连接字符串,服务器,数据库,表都已设置。

任何想法我错过了什么?

2 个答案:

答案 0 :(得分:0)

您错过了con.Open(); inyour code

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); } }

答案 1 :(得分:0)

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

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