0

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?

4
  • 1
    You never set the command's connection. Anyway, SqlCommand is for SQL Server. You should use OleDbCommand Commented Sep 21, 2017 at 8:31
  • 1
    FYI, never call Dispose like that, instead initialize the SqlCommand in a nested using block. That will handle cleanup. Commented Sep 21, 2017 at 8:33
  • @AluanHaddad may I ask why? Commented Sep 21, 2017 at 13:43
  • 1
    Because IDisposables need to be disposed and because you can forget to do so, or do so incorrectly, C# has the using statement 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. Commented Sep 21, 2017 at 21:43

1 Answer 1

1

The connection was created but never set on the command object. BTW SqlCommand is a SQL Server Client command.

Instead of :

var cmd = new SqlCommand("INSERT INTO SUMMARY (A, B, C) VALUES (@A, @B, @C)");

Use

var cmd = new OleDbCommand("INSERT INTO SUMMARY (A, B, C) VALUES (?, ?, ?)",connection);

Access doesn't support named parameters in SQL queries. The parameter values will be substitued by position.

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.