Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created March 29, 2018 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/561e7f02969080e8abb062494cf32781 to your computer and use it in GitHub Desktop.
Save Fhernd/561e7f02969080e8abb062494cf32781 to your computer and use it in GitHub Desktop.
Ejecución de comandos SQL y procedimientos almacenados. OrtizOL.
using System;
using System.Data;
using System.Data.SqlClient;
namespace R905EjecutarComandoSql
{
class R906Programa
{
static void Main(string[] args)
{
using (SqlConnection conexion = new SqlConnection())
{
conexion.ConnectionString = @"Data source =.\SQLEXPRESS; Initial catalog = Northwind;Integrated Security=SSPI";
conexion.Open();
Console.WriteLine("Ejemplo de ExecuteNonQuery:\n");
ExecuteNonQueryEjemplo(conexion);
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Ejemplo de ExecuteReader:\n");
ExecuteReaderEjemplo(conexion);
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Ejemplo de ExecuteScalar:\n");
ExecuteScalarEjemplo(conexion);
Console.WriteLine("\nPresione Enter para continuar...");
Console.ReadLine();
}
}
public static void ExecuteNonQueryEjemplo(IDbConnection conexion)
{
IDbCommand comando = conexion.CreateCommand();
comando.CommandType = CommandType.Text;
comando.CommandText = "UPDATE Employees SET Title = 'Sales Director' WHERE EmployeeId = '5'";
int resultado = comando.ExecuteNonQuery();
if (resultado == 1)
{
Console.WriteLine("Título de empleado -ID = 5- actualizado.");
}
else
{
Console.WriteLine("No se pudo actualizar el título del empleado.");
}
}
public static void ExecuteReaderEjemplo(IDbConnection conexion)
{
IDbCommand comando = conexion.CreateCommand();
comando.CommandType = CommandType.StoredProcedure;
comando.CommandText = "Ten Most Expensive Products";
using (IDataReader lector = comando.ExecuteReader())
{
Console.WriteLine("Precio de los 10 productos más costosos:");
while (lector.Read())
{
Console.WriteLine("{0} = {1}", lector["TenMostExpensiveProducts"], lector["UnitPrice"]);
}
}
}
public static void ExecuteScalarEjemplo(IDbConnection conexion)
{
IDbCommand comando = conexion.CreateCommand();
comando.CommandType = CommandType.Text;
comando.CommandText = "SELECT COUNT(*) FROM Employees";
int resultado = (int) comando.ExecuteScalar();
Console.WriteLine("Cantidad de empleados: {0}", resultado);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment