Click here to Skip to main content
15,922,407 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've a list of hexadecimal number with a data type varbinary. But when I run a query, nothing shown as a result.

What I have tried:

Currently, I'm getting an error:
System.InvalidOperationException: 'Invalid attempt to read when no data is present.'

Can I know what is the best way to fetch the binary data from the database?
Posted
Updated 9-Oct-20 22:19pm
v3
Comments

Use parameters to fix the SQL Injection[^] vulnerabilities in your code.

Wrap all disposable objects in using blocks.

Don't share connection, command, dataadapter, or datareader objects between invocations of your method.

There's no need to use a dataadapter to execute a single update command.
C#
string SNE = data["End_Rg"];

using (var command = new SqlCommand("UPDATE Range SET status = 'Used' WHERE End_SerialNum = @SNE", cnn))
{
    command.Parameters.AddWithValue("@SNE", SNE);
    command.ExecuteNonQuery();
}

using (var command = new SqlCommand("SELECT Start_Range, End_Range, Status FROM SDCard_SNRange WHERE End_SerialNum = @SNE", cnn))
{
    command.Parameters.AddWithValue("@SNE", SNE.Substring(2));
    
    using (var reader = command.ExecuteReader())
    {
        if (reader.HasRows)
        {
            using (var tw = File.AppendText(logPath))
            {
                while (reader.Read())
                {
                    tw.WriteLine("Update status");
                    tw.WriteLine("Start Range: {0}", dataReader["Start_Range"]);
                    tw.WriteLine("End Range: {0}", dataReader["End_Range"]);
                    tw.WriteLine("Status: {0}", dataReader["Status"]);
                }
            }
        }
    }
}
 
Share this answer
 
The error message is clearly telling you that your dataReader does not contain any records. That tells you that the previous query did not find any matching rows. You should check the value you are using as the search criteria in your SELECT clause. But you also need to add checks in all your database code to see whether the requests were successful or not. As it stands your code could run for weeks without ever doing anything correctly and you would never know.

Also take note of the comment above from Richard Deemimg, which is very important.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900