I’m using C# in .NET 2.0 and I’m trying to access and manipulate a database. I can read as many times from the DB as I want and everything works, but as soon as I try to insert an item I get the following error message:
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
I’ve tried to look this up, but the fixes I was able to find either didn’t work or weren’t applicable.
I have the following code:
using (SqlConnection conn = new SqlConnection(SQLConnectionString))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT [Col1] FROM [Table1] WHERE [Col2]='" + val2 + "'", conn);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables.Count == 0 || dataSet.Tables[0].Rows.Count != 1)
{
SqlCommand cmd = new SqlCommand("INSERT INTO [Table1] ([Col1], [Col2]) VALUES ('" + val1 + "', '" + val2 + "')", conn);
cmd.ExecuteNonQuery();
}
}
Note: I’m sure I have permissions set up properly, since Visual Studio can insert with the same SQLConnectionString. Also, I am still fairly new to databases, so if I’m doing anything blantently wrong, please let me know.
Thanks.
You don’t appear to be opening the connection to perform your update (the exception tells you this).
Try this
You can get more details and working example on MSDN at http://msdn.microsoft.com/en-us/library/sd2728ad.aspx