I have a table in a SQL Server 2008 database.
How can I read a row's column value by specifying the column name in a SqlDataReader
after doing a SELECT * FROM table WHERE <row selection>
?
The error is: "Additional information: Invalid attempt to read when no data is present." if I do .GetString before .Close() and "Invalid attempt to call CheckDataIsReady when reader is closed." if I close then do GetString. Or should it be GetSqlString()?
Here's my SQL command:
SELECT * FROM CLIENT_JOBS_TABLE WHERE CLIENT_ID = 'JOES_BURGERS' AND JOB_ID = 'FRY_COOK_2014_07_05'
In my code below, I get an error trying to read the value of column JOB_ID
.
some_data = query_result2.GetString(field_ordinal) ' field_ordinal=1
..gets error: "A first chance exception of type 'System.InvalidOperationException' occurred in System.Data.dll" ..and 'some_data' is set to nothing
Private Function query_SQL_database(ByVal sql_text_command As String, ByRef query_result As SqlDataReader)
' Open the connection
Debug.WriteLine(sql_text_command)
ConnectionString = "Data Source=66.7.250.100;Initial Catalog=ehiresdb;Persist Security Info=True;User ID=Doug;Password=ThankYou!!"
Dim connection As New SqlConnection(ConnectionString)
connection.ConnectionString = ConnectionString
connection.Open()
SQL_command = New SqlCommand(sql_text_command, connection)
Dim command_successful = True
On Error Resume Next
Dim query_result2 As SqlDataReader
query_result2 = SQL_command.ExecuteReader()
If Err.Number Then
command_successful = False
Dim reason = Err.Description
MsgBox(Err.Description, MsgBoxStyle.Exclamation, "issue_SQL_command")
Else
command_successful = True
End If
query_result2.Read() ' <<<<<<<<<<<<<<<<<<<<<<<<<<<< SOLUTION!
field_ordinal = query_result2.GetOrdinal("CLIENT_ID")
field_ordinal = query_result2.GetOrdinal("JOB_ID")
some_data = query_result2.GetString(field_ordinal) <<<<< FAILS BEFORE THE .CLOSE
connection.Close()
Return command_successful
End Function 'issue_SQL_command