问题来了。我正在尝试在 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/