none
Database Insert RRS feed

  • Question

  • hi,

    I am trying to add a row to the table but ad error is always encountered.
    my code is blew :

    string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Database.mdf
                                                          Integrated Security=True;Connect Timeout=30;User Instance=True";

            SqlConnection con = new SqlConnection(ConnectionString);
            SqlCommand cmdInsert = new SqlCommand ("INSERT INTO CUSTOMER   (CUSTOMERID,CName,CFamily)
    VALUES (@CUSTOMERID,@CNAME,@CFAMILY)");


            SqlParameter p1 = new SqlParameter("@CUSTOMERID", SqlDbType.Int);

            SqlParameter p2 = new SqlParameter("@CName", SqlDbType.NVarChar);

            SqlParameter p3 = new SqlParameter("@CFamily", SqlDbType.NVarChar);
            cmdInsert.Parameters.Add(p1);
            cmdInsert.Parameters.Add(p2);
            cmdInsert.Parameters.Add(p3);
            con.Open();
            p1.Value = 0;
            p2.Value = tbName;
            p3.Value = tbFamily;
            cmdInsert.ExecuteNonQuery();
            con.Close();


    and I face this error System.InvalidOperationException: ExecuteNonQuery: Connection property has not been initialized.

    THX

    Source Error:

    Line 40:         p2.Value = tbName;
    Line 41: p3.Value = tbFamily;
    Line 42: cmdInsert.ExecuteNonQuery();
    Line 43: con.Close();
    Line 44: }
    • Moved by Chris Robinson- MSFT Friday, February 27, 2009 11:33 PM Not a dataSet issue, connection issue (Moved from ADO.NET DataSet to ADO.NET Data Providers)
    Friday, February 27, 2009 6:51 PM

Answers

  • Hey Amir,

    You need to initialize the Connection that the Command uses before you query.
    dataCommand.Connection = dataConnection;
     
    Optionally you can use the overloaded SqlCommand constructor:
     
    SqlCommand dataCommand = new SqlCommand(sql, dataConnection); instead of just providing the Sql string
     
    Thanks
    Chris Robinson
    Program Manager - DataSet
     

    This posting is provided "AS IS" with no warranties, and confers no rights.
    Friday, February 27, 2009 11:33 PM