How to DataAdapter Insert Command - Sql Server

The SqlDataAdapter serves as the bridge between the Dataset and the Data Source, utilizing the SqlConnection Object for communication. In addition, the SqlDataAdapter features properties such as InsertCommand, UpdateCommand, and DeleteCommand, which are Command objects responsible for handling updates to the data in the data source based on modifications made to the data within the Dataset.

InsertCommand

The InsertCommand within the SqlDataAdapter manages the insertion of data into the specified Data Source. The following C# Source Code illustrates how to insert data into the Data Source using the SqlDataAdapter and SqlCommand objects. First, establish a connection to the Data Source using the SqlConnection object. Then, create a SqlCommand object with an insert SQL statement and assign this SqlCommand to the InsertCommand property of the SqlDataAdapter. This configuration allows the SqlDataAdapter to effectively execute the insert command against the Data Source when needed.

Full Source C#
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()); } } } }