问题就在这里。我正在尝试执行查询及其抛出和异常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 对象替换我的连接!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)