i

ASP.Net A Complete Guide

Commands

SQL Commands: Allows you to perform the operations like insert, update, delete. The command object uses the connection objects to make a connection to the database. The query which we pass the command is in the form of the inline SQL statement or the stored procedure. SqlCommand's important factor is we can execute SQL queries and procedures directly.

Property of SqlCommand:

  • CommandTimeout: It Specifies that the time to wait when executing the command. Default Time for Execution is 30 Seconds.

  • Connection:  The SqlConnection object that is used provides the entry point of the data source.

  • CommandText:  Represents the Statements or the Stored Procedure.

Methods of SqlCommand:

  • ExecuteNonQuery: This returns the number of affected rows.

  • ExecuteReader: This returns the instance of SqlDataReader.

  • ExecuteScalar: This returns the first column of the first row of the result set. The remaining column & row are ignored.

Syntax of SqlCommand:

SqlCommand cmd = new SqlCommand(); 

cmd.Connection = conn; 

 

Example:

public void CallToCommand() 

    Sqlconnectionection connection = new Sqlconnectionection(); 

    connection.connectionectionString = ConfigurationManager.connectionectionStrings["connectionString"].connectionectionString; 

    try 

    { 

        SqlCommand command = new SqlCommand(); 

        command.connectionection = connection; 

        command.CommandText = "DELETE FROM EMPLOYEE WHERE DEPTID = 40"; 

        command.CommandType = CommandType.Text; 

        connection.Open(); 

        int AffectedRow = command.ExecuteNonQuery(); 

        MessageBox.Show(AffectedRow + " rows affected", "Message"); 

        command.Dispose(); 

        connection.Dispose(); 

    } 

    catch (Exception ex) 

    { 

        MessageBox.Show(ex.Message); 

    } 

}