none
Insert Command with SqlDataAdapter RRS feed

  • Question

  • We Know in SqldataAdapter we can only Pass the Select Command. 

     SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True");
    SqlDataAdapter da=new SqlDataAdapter("Insert Into Employee values("+textBox1.Text+",'"+textBox2.Text+"','"+textBox3.Text+"',"+textBox4.Text+")",con);  DataSet ds = new DataSet();
    da.Fill(ds);

    But it works. Thats means we can directly pass the insert,update, delete command into

    SqlDataadapter.Can any one Explain it briefly? 

    Saturday, November 3, 2012 7:59 AM

Answers

  • Hi Rajesh,

    You are right, we use Select command in Adapter but we cannot say it is only select command, Query can be any DML statements, when you execute the DataAdapter it actually executes the query mentioned in the parameter.

    There is one another way to insert using Adapter:

     SqlCommand command = new SqlCommand("SELECT * FROM Customers " +
            "WHERE Country = @Country AND City = @City", connection);
    
        // Add the parameters for the SelectCommand.
        command.Parameters.Add("@Country", SqlDbType.NVarChar, 15);
        command.Parameters.Add("@City", SqlDbType.NVarChar, 15);
    
        adapter.SelectCommand = command;
    
        // Create the InsertCommand.
        command = new SqlCommand(
            "INSERT INTO Customers (CustomerID, CompanyName) " +
            "VALUES (@CustomerID, @CompanyName)", connection);
    
        // Add the parameters for the InsertCommand.
        command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
        command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
    
        adapter.InsertCommand = command;
    See, i have written two scenario, Select and Insert using Adapter, that means we can perform DML Operations as well.



    Sunday, November 4, 2012 5:17 AM