SqlConnection.Open()解决思路
SqlConnection.Open()
请问在一个Sub里使用SqlConnection和SqlCommand,当跳出Sub时,需不需要把SqlConnection和SqlCommand设为Nothing,并SqlConnection.Close() ???
因为如果预到异常时,Sub可能会中止,这样的话SqlConnection和SqlCommand会不会还存活着?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim SqlConnection1 As New System.Data.SqlClient.SqlConnection
Dim SqlCommand1 As New System.Data.SqlClient.SqlCommand
SqlConnection1.ConnectionString = strModConnectionString
SqlCommand1.Connection = SqlConnection1
SqlConnection1.Open()
SqlCommand1.CommandText = "Select count(*) from Table "
Msgbox "SqlCommand1.ExecuteScalar() "
'需不需要加入这几行代码?
SqlCommand1=Nothing
SqlConnection1.Close()
SqlConnection1=Nothing
End Sub
------解决方案--------------------
根据我遇到的情况,这里面的对象还存在,你可以使用try 块去控制它,
Dim SqlConnection1 As System.Data.SqlClient.SqlConnection
Dim SqlCommand1 As System.Data.SqlClient.SqlCommand
try
sqlconnection1 = new sqlclient.sqlconnect
SqlConnection1.ConnectionString = strModConnectionString
sqlcommand1= new sqlclient.sqlcommand
SqlCommand1.Connection = SqlConnection1
SqlConnection1.Open()
SqlCommand1.CommandText = "Select count(*) from Table "
Msgbox "SqlCommand1.ExecuteScalar() "
Catch ex As Exception
msgbox ex.massage
finally
SqlCommand1=Nothing
SqlConnection1.Close()
SqlConnection1=Nothing
end try
这样可以在发生错误后,将连接对象释放掉
------解决方案--------------------
只需要SqlConnection1.Close()就行了
如果是2005,用Using conn as new sqlconnection()
........
end using
这样它会自动释放掉
请问在一个Sub里使用SqlConnection和SqlCommand,当跳出Sub时,需不需要把SqlConnection和SqlCommand设为Nothing,并SqlConnection.Close() ???
因为如果预到异常时,Sub可能会中止,这样的话SqlConnection和SqlCommand会不会还存活着?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim SqlConnection1 As New System.Data.SqlClient.SqlConnection
Dim SqlCommand1 As New System.Data.SqlClient.SqlCommand
SqlConnection1.ConnectionString = strModConnectionString
SqlCommand1.Connection = SqlConnection1
SqlConnection1.Open()
SqlCommand1.CommandText = "Select count(*) from Table "
Msgbox "SqlCommand1.ExecuteScalar() "
'需不需要加入这几行代码?
SqlCommand1=Nothing
SqlConnection1.Close()
SqlConnection1=Nothing
End Sub
------解决方案--------------------
根据我遇到的情况,这里面的对象还存在,你可以使用try 块去控制它,
Dim SqlConnection1 As System.Data.SqlClient.SqlConnection
Dim SqlCommand1 As System.Data.SqlClient.SqlCommand
try
sqlconnection1 = new sqlclient.sqlconnect
SqlConnection1.ConnectionString = strModConnectionString
sqlcommand1= new sqlclient.sqlcommand
SqlCommand1.Connection = SqlConnection1
SqlConnection1.Open()
SqlCommand1.CommandText = "Select count(*) from Table "
Msgbox "SqlCommand1.ExecuteScalar() "
Catch ex As Exception
msgbox ex.massage
finally
SqlCommand1=Nothing
SqlConnection1.Close()
SqlConnection1=Nothing
end try
这样可以在发生错误后,将连接对象释放掉
------解决方案--------------------
只需要SqlConnection1.Close()就行了
如果是2005,用Using conn as new sqlconnection()
........
end using
这样它会自动释放掉