What am I not understanding in the following code:
using (OleDbConnection connectionFail = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Fail_DB.mdb"))
{
connectionFail.Open();
var cmd = new SqlCommand("INSERT INTO SUMMARY (A, B, C) VALUES (@A, @B, @C)");
cmd.Parameters.Add("@A", SqlDbType.NVarChar, 50).Value = "A";
cmd.Parameters.Add("@B", SqlDbType.NVarChar, 50).Value = "B";
cmd.Parameters.Add("@C", SqlDbType.NVarChar, 50).Value = "C";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
connectionFail.Close();
cmd.Dispose();
}
connectionFail.Close();
}
}
I just want to add data to a SUMMARY table. I get ExecuteNonQuery:Connection property has not been initialized. What am I not understanding?
Disposelike that, instead initialize theSqlCommandin a nested using block. That will handle cleanup.IDisposables need to be disposed and because you can forget to do so, or do so incorrectly, C# has theusingstatement which automates the process. This improves maintainability, raises the abstraction level slightly, is idiomatic, and does not hijack exception handling machinery to perform expected cleanup.