W
Woody Splawn
I have some code which I will show below that opens a SQLDataReader, gets
some information and then closes. My question is, what is the proper way to
close? Do I close the reader first and then attempt to close SQLCommand and
the SQLConnection? Do I close the SQLCommand and the SQLConnection and then
the SQLDataReader? Do I need to check the conneciton state for each?
What is the proper way?
mySqlConnection = New SqlConnection(myConnectionString)
Dim sql_Command As New SqlCommand( _
"Select * from VSPW", _
mySqlConnection)
Try
mySqlConnection.Open()
Dim myReader As SqlDataReader =
sql_Command.ExecuteReader(CommandBehavior.CloseConnection)
While myReader.Read()
psMasterPW = myReader.GetString(0) ' The first field in the
answer set
psEditARPW = myReader.GetString(1) 'The second field in the
answer set
psPrintPW = myReader.GetString(2) 'The third field in the
answer set
End While
'myReader.Close()
'sql_Command.Connection.Close()
'If mySqlConnection.State = ConnectionState.Open Then
' mySqlConnection.Close()
'End If
Catch ex As SqlException
MessageBox.Show(ex.ToString, "Exception Error")
Finally
If sql_Command.Connection.State = ConnectionState.Open Then
sql_Command.Connection.Close()
End If
If mySqlConnection.State = ConnectionState.Open Then
mySqlConnection.Close()
End If
sql_Command.Connection.Close()
End Try
some information and then closes. My question is, what is the proper way to
close? Do I close the reader first and then attempt to close SQLCommand and
the SQLConnection? Do I close the SQLCommand and the SQLConnection and then
the SQLDataReader? Do I need to check the conneciton state for each?
What is the proper way?
mySqlConnection = New SqlConnection(myConnectionString)
Dim sql_Command As New SqlCommand( _
"Select * from VSPW", _
mySqlConnection)
Try
mySqlConnection.Open()
Dim myReader As SqlDataReader =
sql_Command.ExecuteReader(CommandBehavior.CloseConnection)
While myReader.Read()
psMasterPW = myReader.GetString(0) ' The first field in the
answer set
psEditARPW = myReader.GetString(1) 'The second field in the
answer set
psPrintPW = myReader.GetString(2) 'The third field in the
answer set
End While
'myReader.Close()
'sql_Command.Connection.Close()
'If mySqlConnection.State = ConnectionState.Open Then
' mySqlConnection.Close()
'End If
Catch ex As SqlException
MessageBox.Show(ex.ToString, "Exception Error")
Finally
If sql_Command.Connection.State = ConnectionState.Open Then
sql_Command.Connection.Close()
End If
If mySqlConnection.State = ConnectionState.Open Then
mySqlConnection.Close()
End If
sql_Command.Connection.Close()
End Try