Methods ExecuteReader (), ExecuteNonQuery () and ExecuteScalar (), what are the differences and how to use them?

11

I'm working with SQL Server database in C #, but I noticed that the SqlCommand object has several methods to execute a query , they are: ExecuteReader() , ExecuteNonQuery() and ExecuteScalar() .

My question is, what are the differences between these methods and how should I use them?

    
asked by anonymous 24.10.2015 / 00:26

1 answer

12

ExecuteReader

Used to perform field-to-field reading on a data extraction. This is done through the object of type SqlDataReader returned by the method.

Example:

using (var connection = new SqlConnection(
           connectionString))
{
    connection.Open();

    var command = new SqlCommand("Select * from MinhaTabela", connection);
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        for(int i = 0 ; i < count ; i++) {
            Console.WriteLine(reader.GetValue(i));
        }
    }
}

This is a rather verbose method for direct column access.

ExecuteNonQuery

Executes a command that does not have a row and column relationship. Your return is actually the number of rows affected by the command.

Used for sentences like INSERT , UPDATE , DELETE , etc.

Example:

using (var connection = new SqlConnection(
           connectionString))
{
    var command = new SqlCommand("UPDATE MinhaTabela set MeuCampo = 1 where OutroCampo = 2", connection);
    command.Connection.Open();
    var registrosAfetados = command.ExecuteNonQuery();
}

ExecuteScalar

Executes a command and returns the first column of the first row returned. Usually useful for executing, for example, Stored Procedures that returns a specific value or functions as a count of records.

Example:

using (var connection = new SqlConnection(connString))
{
    var cmd = new SqlCommand(conn);
    cmd.CommandText = "SELECT COUNT(*) FROM MinhaTabela";

    try
    {
        conn.Open();
        var contagem = (Int32)cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
    
24.10.2015 / 00:44