C#连接数据库的问题,请各位解答
private void AddStudentForm_Load(object sender, EventArgs e){
try
{
string connString = "Data Source=.;Initial Catalog=news;User ID=sa";
SqlConnection connection = new SqlConnection(connString);
connection.Open();
//查询年级的sql语句
string sql = "select TitleName from FirstLevelTitle";
//定义Command对象
SqlCommand command = new SqlCommand(sql, connection);
SqlDataReader dataReader = command.ExecuteReader();
//年级名称
string gradeName = "";
//循环读出所有年级并添加到年级组合框中
while (dataReader.Read())
{
gradeName = (string)dataReader[0];
listBox1.Items.Add(gradeName);
}
dataReader.Close();
}
catch (Exception ex)
{
MessageBox.Show("数据库操作错误");
}
//下面的finally关不掉
finally
{
connection.Close(); //为什么这句找不到,没有connection }
}
finally下面没有connection对象,也就没有close方法了,不知怎么回事