How to DataAdapter Insert Command - Sql Server

SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . InsertCommand , UpdateCommand , and DeleteCommand properties of the SqlDataAdapter are Command objects that manage updates to the data in the data source according to modifications made to the data in the DataSet.

The InsertCommand in SqlDataAdapter Object manages to insert the data in the specified Data Source . The following C# Source Code shows how to insert data in the Data Source using SqlDataAdapter and SqlCommand object. Open a connection to the Data Source with the help of SqlConnection object and create a SqlCommand object with insert SQL statement, and assign the SqlCommand to the SqlDataAdapter's InsertCommand.




using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection ;
            SqlDataAdapter adapter = new SqlDataAdapter();
            string sql = null;
            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            connection = new SqlConnection(connetionString);
            sql = "insert into product (Product_id,Product_name,Product_price) values(6,'Product6',600)";
            try
            {
                connection.Open();
                adapter.InsertCommand = new SqlCommand(sql, connection);
                adapter.InsertCommand.ExecuteNonQuery();
                MessageBox.Show ("Row inserted !! ");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

 CSharp DataAdapter - Related Contents


 CSharp DataAdapter - Related Programs

.