Click here to Skip to main content
15,904,822 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is my code where i want to insert data into the database if "testheader" is not null.

and I get error

"
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.

"
when I tried it without any validation then data inserted successfully.

What I have tried:

c# code....

public bool InsertCustomizeRowtwo(string cocode,string dept, string testcode,string testname,string testheader,string sub1,string sub2,string sub3,string sub4,string sub5,string sub6,string sub7,string sub8, string sub9,string sub10)

{
if (testheader == "")
testheader = null;
try
{
//connection
theConnection = new SqlConnection();
if (conString != "")
{
theConnection.ConnectionString = conString;
theConnection.Open();

}
//command
theCommand = new SqlCommand();
theCommand.Connection = theConnection;
if (testheader != null)
{
theCommand.CommandText = "insert into PH_TestMaster_CustRowtwo(COMPCODE,DEPARTMENT,TESTCODE,TESTNAME,TEST_HEADER,TEST_SUB1,TEST_SUB2,TEST_SUB3,TEST_SUB4,TEST_SUB5,TEST_SUB6,TEST_SUB7,TEST_SUB8,TEST_SUB9,TEST_SUB10) VALUES('" + cocode + "','" + dept + "','" + testcode + "','" + testname + "','" + testheader + "','" + sub1 + "','" + sub2 + "','" + sub3 + "','" + sub4 + "','" + sub5 + "','" + sub6 + "','" + sub7 + "','" + sub8 + "','" + sub9 + "','" + sub10 + "')";

}
else
{
theConnection.Dispose();
theCommand.Dispose();
}
theCommand.CommandType = CommandType.Text;
theCommand.ExecuteNonQuery();
return true;


}
catch
{
return false;
}
finally
{
theConnection.Dispose();
theCommand.Dispose();

}


}
Posted
Updated 16-Sep-16 21:38pm
Comments
Karthik_Mahalingam 17-Sep-16 3:36am    
make sure the conString is not empty

1 solution

Look at your code (I'll rip out the irrelevancies):
C#
if (testheader != null)
    {
    ...
    }
else
    {
    theConnection.Dispose();
    theCommand.Dispose();
    }
theCommand.CommandType = CommandType.Text;
theCommand.ExecuteNonQuery();
So when testheader is null, you dispose of an object and then immediately try to use it.
That won't work, not ever. And When you try it's like feeding your car into a car-crushing machine and then trying to drive it to the shops afterwards. Doesn't work.

And seriously, never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
You may find your whole problem disappears if you use parameterised queries and dump the testheader null check.
 
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