Click here to Skip to main content
15,917,320 members
Please Sign up or sign in to vote.
4.11/5 (2 votes)
See more:
Hello all,

I have a method that i use to run SQL queries.

The problem is that even though i close the connection to the database all the time i keep getting an error that the current state of the connection is still open. That causes my whole application to break

I don't know why this is happening as this code worked 100% in another web application with out getting this error.

Any insight will be very helpful

Here is a code sample

C#
private static String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString;
    
private static SqlConnection SQLConnection = new SqlConnection(connectionString);

public static void runSQL(String SQL)
    {
        SQLCommand = new SqlCommand(SQL, SQLConnection);

        SQLConnection.Open();
        SQLCommand.ExecuteNonQuery();
        SQLConnection.Close();
    }
Posted
Comments
ZurdoDev 10-Jun-14 9:24am    
Are you sure this is where the error is coming from?
Member 10395722 10-Jun-14 9:25am    
Im not sure? Ive noticed it happens after running an sql query
ZurdoDev 10-Jun-14 9:26am    
Since you do have close here I would doubt this is it. Unless ExecuteNonQuery throws an exception then close won't run. You could put this in a try catch with finally being to close if it's still open.
Member 10395722 10-Jun-14 9:30am    
That makes sense, it could be that the execution doesn't finish and never gets to close the connection. Do you have any idea why this would be happening?
[no name] 10-Jun-14 9:25am    
Why would you use a static variable in a web application?

Couple of Suggestions...

1. Don't use Static Variables, otherwise it would remain as intact.
2. Put try, catch and finally blocks in your code.
3. Close the connection inside the finally block.

Update your code to reflect these changes and try again.
 
Share this answer
 
 
Share this answer
 

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