这是问题所在。我试图在connection.Open
执行查询及其抛出和异常。奇怪的是,在同一个应用程序上,我正在执行“选择”查询,它工作正常。但是当我执行“更新”查询时,它会抛出此Unable连接到任何指定的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");
}
答案 0 :(得分:1)
我建议你做以下事情:
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");
}
}
我知道你在想自己,你应该保持联系以便于使用和等等等等,但根据我的经验,这是浪费精力。什么最终会发生你不想要或不需要的麻烦。您最终没有意识到您在其他地方打开了连接,并且您花费数小时来解决您不应该做的事情。打开你的连接,完成后关闭它。
如果你想拥有一个连接对象,那很好,但是使用使用模式以便每次都处理它,并且总是从你的连接开始。
注意:用yoru MySqlConnection对象替换我的连接!
答案 1 :(得分:0)
正如迈克所说,你总是更好地使用“使用”块,因为它一旦停止使用块就会处理任何连接。我在下面使用了两个用于连接的块,而另一个用于命令对象。
试试这个
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connString))
{
if (radioButton1.Checked)
{
timerEnabled = 1;
}
string queryString = "update Admin_Settings set Difficulty='" +
comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," +
"NoOfChoices='" + comboBox5.Text + "'," + "Subject='" + comboBox8.Text +
"'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled +
"," + "TimerType='" + comboBox1.Text + "'";
using (SqlCommand command = new SqlCommand(queryString, connection))
{
//update the settings to the database table
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
MessageBox.Show("Settings updated");
}
}
}