我有一个错误,其中显示连接未关闭 我甚至尝试过最后但是它不起作用
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "SELECT * FROM Dataaa WHERE FirstName='" + comboBox1.Text + "'";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txt_EID.Text = reader["EID"].ToString();
textBox1.Text = reader["Firstname"].ToString();
textBox2.Text = reader["LastName"].ToString();
textBox3.Text = reader["ICNO"].ToString();
textBox4.Text = reader["Address"].ToString();
textBox5.Text = reader["Loan"].ToString();
textBox6.Text = reader["Percent"].ToString();
textBox7.Text = reader["Payback"].ToString();
textBox8.Text = reader["StartDate"].ToString();
textBox9.Text = reader["EndDate"].ToString();
textBox10.Text = reader["Monthly"].ToString();
textBox11.Text = reader["PaymentType"].ToString();
textBox12.Text = reader["Remark"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("error " + ex);
}
答案 0 :(得分:1)
而不是连接。手动关闭,在'使用'中创建连接。块:
using(var connection = new SqlConnection(...))
{
OleDbCommand command = new OleDbCommand();
........
}
这样您就不必担心关闭连接。一旦使用块结束,连接也会结束。