//Metodo para llenar un DataTable public static DataTable getDatosTabla(string nombreProcedimiento, string[] nombreParametros, params Object[] valoresDeParametros) { DataTable dataTable = new DataTable(); SqlCommand cmd = new SqlCommand(); Conexion conexion = new Conexion(); cmd.Connection = conexion.getConexion(); cmd.CommandText = nombreProcedimiento; cmd.CommandType = CommandType.StoredProcedure; if (nombreProcedimiento.Length != 0 && nombreParametros.Length == valoresDeParametros.Length) { int i = 0; if (nombreParametros != null && valoresDeParametros != null) { foreach (string parametro in nombreParametros) cmd.Parameters.AddWithValue(parametro, valoresDeParametros[i++]); } try{ SqlDataReader dataReader = cmd.ExecuteReader(); dataTable.Load(dataReader); return dataTable; } catch (Exception){ throw new Exception("Error en la consulta."); } } return dataTable; }
//metodo ejecutar procedimiento por ejemplo insert,delete,update,select public int Ejecutar(String nomprocedimiento,string [] nomparametros,params Object[]valparametros) { Conexion con = new Conexion(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con.getConexion(); cmd.CommandText = nomprocedimiento; cmd.CommandType = CommandType.StoredProcedure; if (nomprocedimiento.Length!=0 && nomparametros.Length == valparametros.Length) { int posicionParametro = 0; StringBuilder errorMessages = new StringBuilder(); foreach (string parametro in nomparametros) { cmd.Parameters.AddWithValue(parametro, valparametros[posicionParametro++]); } return cmd.ExecuteNonQuery(); } con.cerrarConexion(); return 0; }
//metodo para llenar un Data Table public DataTable getDatosTabla(String nomprocedimiento, string[] nomparametros, params Object[] valparametros) { DataTable dt = new DataTable(); SqlCommand cmd = new SqlCommand(); Conexion con = new Conexion(); cmd.Connection = con.getConexion(); cmd.CommandText = nomprocedimiento; cmd.CommandType = CommandType.StoredProcedure; if (nomprocedimiento.Length != 0 && nomparametros.Length == valparametros.Length) { int posicionParametro = 0; StringBuilder errorMessages = new StringBuilder(); foreach (string parametro in nomparametros) { cmd.Parameters.AddWithValue(parametro, valparametros[posicionParametro++]); } SqlDataReader dr = cmd.ExecuteReader(); dt.Load(dr); return dt; } return dt; }
//Metodo para ejecutar Store Procedures public static int Ejecutar(string nombreProcedimiento, string[] nombreParametros, params Object[] valoresDeParametros) { Conexion conexion = new Conexion(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conexion.getConexion(); cmd.CommandType = CommandType.StoredProcedure; if (nombreProcedimiento.Length != 0 && nombreParametros.Length == valoresDeParametros.Length) { int i = 0; foreach (string parametro in nombreParametros) cmd.Parameters.AddWithValue(parametro, valoresDeParametros[i++]); try{ return cmd.ExecuteNonQuery(); } catch (Exception) { return 1; } } return 0; }