Created
March 29, 2018 12:59
-
-
Save Fhernd/561e7f02969080e8abb062494cf32781 to your computer and use it in GitHub Desktop.
Ejecución de comandos SQL y procedimientos almacenados. OrtizOL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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