Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement