C# ADO.NET OleDbCommand - ExecuteNonQuery

The ExecuteNonQuery() method holds significant importance within the OleDbCommand Object and is widely employed for executing statements that do not return result sets. This method serves a dual purpose, enabling both Data Definition and Data Manipulation tasks.

ExecuteNonQuery() methods

Data Definition tasks encompass operations such as creating Stored Procedures, Views, or modifying the structure of the database. The ExecuteNonQuery() method efficiently handles these tasks by executing the corresponding SQL statements provided.

cmd.ExecuteNonQuery();

Moreover, the ExecuteNonQuery() method also caters to Data Manipulation tasks, which involve operations such as inserting, updating, or deleting data within the database. By invoking the ExecuteNonQuery() method with the appropriate SQL statement, developers can seamlessly perform these crucial data manipulation operations.

The following C# example shows how to use the method ExecuteNonQuery() through OleDbCommand Object.

Full Source C#
using System; using System.Windows.Forms; using System.Data.OleDb; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connetionString = null; OleDbConnection cnn ; OleDbCommand cmd ; string sql = null; connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here" cnn = new OleDbConnection(connetionString); try { cnn.Open(); MessageBox.Show("Connection Opened "); cmd = new OleDbCommand(sql, cnn); cmd.ExecuteNonQuery(); cmd.Dispose(); cnn.Close(); MessageBox.Show (" ExecuteNonQuery in OleDbConnection executed !!"); } catch (Exception ex) { MessageBox.Show("Can not open connection ! " + ex.ToString()); } } } }

Conclusion

The versatility of the ExecuteNonQuery() method lies in its ability to execute both Data Definition and Data Manipulation tasks, making it a go-to choice for numerous database operations. Whether you need to create database objects or modify data, the ExecuteNonQuery() method provides a reliable and efficient means to accomplish these tasks.