Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用参数重构查询后的MySQL连接问题_C#_Mysql_Ado.net - Fatal编程技术网

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

C# 使用参数重构查询后的MySQL连接问题,c#,mysql,ado.net,C#,Mysql,Ado.net,我试图用参数化查询重构代码 代码试图基于两个文本框(student_lastname和student_name)将数据插入MySQL数据库。但我似乎在联系上犯了某种错误 以下是我的尝试: static string conString = ConfigurationManager.ConnectionStrings["SchoolGrades.Properties.Settings.ConnectionString"].ConnectionString; DataTable dt = new D

我试图用参数化查询重构代码

代码试图基于两个文本框(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\u Click-我就会得到一个错误:
连接没有打开

我已经仔细检查了-连接字符串、服务器、数据库、表都已设置好


你知道我遗漏了什么吗

您缺少
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();
    ....
}

不知道为什么有人否决了这个问题。我想我们只应该考虑这里值得图灵奖的问题。是的,这是一个简单的错误。但是我对这门语言还是很陌生。。