在以上的举例中,我们注意到,这里只关闭了DataReader,并没有关闭Connection。为什么呢?仔细观察以上的ExecuteReader方法,原来,设置了ExecuteReader参数,当执行完ExecuteReader以后,会自动关闭Connection。所以,这样设置以后,就没有必要再手动关闭Connection了。
(2)举例二
Dim myConnection As SqlConnection = new SqlConnection(ConfigurationSettings.AppSettings("DSN_pubs"))
Dim myCommand As SqlCommand = new SqlCommand("Select pub_id, pub_name From publishers", myConnection)
Try
myConnection.Open()
DropDownList1.DataSource = myCommand.ExecuteReader()
DropDownList1.DataBind()
Catch myException As Exception
Response.Write("An error has occurred: " & myException.ToString())
Finally
If Not myConnection Is Nothing AndAlso ((myConnection.State And ConnectionState.Open) = ConnectionState.Open) Then
myConnection.Close()
End If
End Try
Dim myCommand As SqlCommand = new SqlCommand("Select pub_id, pub_name From publishers", myConnection)
Try
myConnection.Open()
DropDownList1.DataSource = myCommand.ExecuteReader()
DropDownList1.DataBind()
Catch myException As Exception
Response.Write("An error has occurred: " & myException.ToString())
Finally
If Not myConnection Is Nothing AndAlso ((myConnection.State And ConnectionState.Open) = ConnectionState.Open) Then
myConnection.Close()
End If
End Try
在以上的举例中,我们发现,居然没有关闭DataReader。为什么呢?其实上面的代码中,没有直接生成DataReader对象,当然也就无从关闭了。需要注意一点的是,在关闭Connection之前,程序首先判断Connection是否已经打开,如果没有打开,也就没必要关闭了。