mysql连接问题

ymzxtsji  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(340)

我正在尝试用参数化查询重构代码。
代码试图将数据插入mysql数据库,基于两个文本框-student\u lastname和student\u name。但我好像在连接上犯了点错误。
以下是我的尝试:

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\u click-我就会得到一个错误: The connection is not open .
我已经仔细检查了-连接字符串、服务器、数据库、表都设置好了。
你知道我遗漏了什么吗?

nxowjjhe

nxowjjhe1#

创建连接对象后,应打开与的连接 Open 功能。

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

3zwjbxry2#

你错过了 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); } }

相关问题