c# - 无法连接到任何指定的 MySQL 主机

标签 c# mysql visual-studio-2010

问题来了。我正在尝试在 connection.Open 处执行查询及其抛出和异常。奇怪的是,在同一个应用程序上我正在执行一个“选择”查询并且它工作正常。但是当我执行“更新”查询时,它会抛出此无法连接到任何指定的 MySQL 主机错误。一直卡在这个上面。有人可以发现我哪里出错了。

 private void button1_Click(object sender, EventArgs e)
    {
        if (radioButton1.Checked)
        {
            timerEnabled = 1;
        }

        connection.Open();

        //update the settings to the database table 
        MySqlCommand command = connection.CreateCommand();
        command.CommandText = "update Admin_Settings set Difficulty='" + comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," + "NoOfChoices='" + comboBox5.Text + "'," +
            "Subject='" + comboBox8.Text + "'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled + "," + "TimerType='" + comboBox1.Text + "'";


        command.ExecuteNonQuery();

        MessageBox.Show("Settings updated");
    }

最佳答案

我建议您执行以下操作:

private void button1_Click(object sender, EventArgs e)
        {
            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connString))
            {
                if (radioButton1.Checked)
                {
                    timerEnabled = 1;
                }

                connection.Open();

                //update the settings to the database table 
                MySqlCommand command = connection.CreateCommand();
                command.CommandText = "update Admin_Settings set Difficulty='" + comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," + "NoOfChoices='" + comboBox5.Text + "'," +
                    "Subject='" + comboBox8.Text + "'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled + "," + "TimerType='" + comboBox1.Text + "'";


                command.ExecuteNonQuery();

                MessageBox.Show("Settings updated");
            }
        }

我知道您在想自己应该保持连接以便于使用等等,但根据我的经验,这是白费力气。最终会发生很多你不想要或不需要的麻烦。您最终没有意识到您在其他地方打开了一个连接,并且您花费数小时来解决您不应该做的事情。打开您的连接,完成后关闭它。

如果你想要一个单一的连接对象,那很好,但是使用 using 模式,这样它每次都会被处理掉,并且总是从你的连接开始。

注意:用 yoru MySqlConnection 对象替换我的连接!

关于c# - 无法连接到任何指定的 MySQL 主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15124040/

相关文章:

visual-studio - 当我在代码编辑器中选择文本时 Visual Studio 崩溃

c++ - 告诉 VS2010 折叠区域

c# - winforms 将换行符(environmental.Newline)添加到代码中的文本框不起作用

c# - C#模拟键盘输入

php - 如何用这样的php变量检查数据库?

php - 使用表连接选择特定数据

c# - 使用 MySQL 参数创建新用户

c# - 过滤然后以元组为键对字典求和

mysql - 在没有mysql的情况下运行wordpress网站

c++ - 决策搜索树中的 LINK 错误 2019 和 1120