0

I have the following script to fetch me some data from a database and then remove it:

public void checkDB()
{
    string query = "SELECT * FROM dbt";

    SqlCommand sqlCommand = new SqlCommand(query, conn);

    SqlDataReader reader;
    int id = -1;

    using (reader = sqlCommand.ExecuteReader())
    {
            if (reader.Read())
            {
                String data= reader["sdata"].ToString();
                Order o = new Order(reader["sdata"].ToString());
                o.prepareForScript();
                id = reader.GetSqlInt32(1).Value;
            }

            reader.Close();
    }

    if (id != -1)
    {
        string removeQuery = "DELETE FROM data WHERE ID=" + id;

        SqlCommand removeCMD = new SqlCommand(removeQuery, conn);

        removeCMD.ExecuteNonQuery();
    }
}

This code results in an exception

unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

with the aditional information that a reader is already associated with this connection. However as you can see the reader is both closed and inside a using loop meaning that it should definitly be closed. Anybody know how to fix this?

8
  • stackoverflow.com/questions/5440168/… Commented Aug 5, 2015 at 8:44
  • Try wrapping your SQL commands in a using also. see stackoverflow.com/questions/16985876/… Commented Aug 5, 2015 at 8:46
  • May be the conn problem. Have you tried to close the conn after SELECT query & open for DELETE query. Commented Aug 5, 2015 at 8:49
  • SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection Commented Aug 5, 2015 at 9:05
  • @Marc_s I'm aware of the risk however I'm pulling an int from a database and then sending it back for deletion that shouldn't be a risk here right? Commented Aug 5, 2015 at 9:15

1 Answer 1

4

You need to dispose first SqlCommand as below :

using (SqlCommand sqlCommand = new SqlCommand(query, conn))
{
        SqlDataReader reader;
        int id = -1;

        using (reader = sqlCommand.ExecuteReader())
        {
            if (reader.Read())
            {


                String data= reader["sdata"].ToString();
                Order o = new Order(reader["sdata"].ToString());
                o.prepareForScript();
                id = reader.GetSqlInt32(1).Value;
            }
            reader.Close();
        }
}

Or

enable MultipleActiveResultSets. This way SQL Server allows several open data readers on a single connection.

But i would suggest not to use your SQL statements together to avoid Sql Injection.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.