Used to perform a field-to-field reading on top of a data extraction. This is done through the type object 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));
}
}
}
It is a rather prolix method for direct access to columns.
Executes a command that does not carry a row and column relation. Its return is actually the amount of rows affected by the command.
It is 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();
}
Executes a command and brings as a result the first column of the first row returned. It is usually useful to run, for example, Stored Procedures which return a specific value or functions such as counting 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);
}
}
Gypsy thanks for the explanation, already this helping me a lot here, now I know how to make better use of these methods.
– gato
@Gypsy good explanation...
– Marco Souza
Only one detail in @Gypsy’s reply.... Executenonquery returns the number of affected rows and not the number of columns. Fountain
– Wemerson Guimarães
@Wemersonguimarães Truth. Thank you!
– Leonel Sanches da Silva