/// <summary> /// Actualiza datos de un jugador /// </summary> /// <param name="newDatosJugador"></param> /// <returns></returns> public int updateJugador(Entidades.Jugador datosJugador) { DataBase _db = new DataBase(); int affectedRows = 0; try { _db.startDB(); _db.Sql = _db.DbConnection.CreateCommand(); _db.Sql.BindByName = true; _db.Sql.CommandType = CommandType.StoredProcedure; _db.Sql.CommandText = "CONSULTAS.GRABAR_JUGADOR"; _db.Sql.Parameters.Add("v_nombre", OracleDbType.Varchar2, datosJugador.nombre, ParameterDirection.Input); _db.Sql.Parameters.Add("v_equipo", OracleDbType.Varchar2, datosJugador.equipoJugador, ParameterDirection.Input); _db.Sql.Parameters.Add("v_direccion", OracleDbType.Varchar2, datosJugador.direccion, ParameterDirection.Input); _db.Sql.Parameters.Add("v_puesto_h", OracleDbType.Varchar2, datosJugador.puestoHab, ParameterDirection.Input); _db.Sql.Parameters.Add("v_fec_na", OracleDbType.Date, datosJugador.fechaNac, ParameterDirection.Input); _db.Sql.Parameters.Add("v_foto", OracleDbType.Blob, datosJugador.avatar, ParameterDirection.Input); affectedRows = _db.execSQL(); } catch (Exception e) { throw new Exception("Error en updateJugador(): " + e.Message); } finally { _db.closeDB(); } return(affectedRows); }
/// <summary> /// Actualiza un jugador de la base de datos /// </summary> /// <param name="jugador"></param> public void Update(Entidades.Jugador jugador) { //Creamos la conexión a utilizar. //Utilizamos la sentencia Using para asegurarnos de cerrar la conexión y liberar el objeto al salir de esta sección de manera automática SqlConnection oCnn = Presentación.Conexion.CrearConexion(); try { using (oCnn) { //Abrimos conexion oCnn.Open(); //Creamos un comando para realizar la modificación del jugador en la base de datos SqlCommand oCmd = new SqlCommand(); using (oCmd) { //Asignamos la conexion de trabajo oCmd.Connection = oCnn; //Indicamos la sentencia SQL oCmd.CommandText = "UPDATE Jugadores SET nroDoc = @nroDoc, tipoDoc = @tipoDoc, nombre = @nombre, apellido = @apellido, sexo = @sexo, direccion = @direccion, localidad = @localidad, telefono = @telefono, telCelular = @telCelular, email = @email, fechaNacimiento = @fechaNacimiento, eloLocal = @eloLocal, idFide = @idFide, idInstitucion = @idInstitucion, baja = @baja WHERE idJugador = @idJugador"; //Asignamos los parámetros oCmd.Parameters.Add("@idJugador", SqlDbType.Int).Value = jugador.idJugador; oCmd.Parameters.Add("@nroDoc", SqlDbType.VarChar, 50).Value = jugador.nroDoc; oCmd.Parameters.Add("@tipoDoc", SqlDbType.VarChar, 50).Value = jugador.tipoDoc; oCmd.Parameters.Add("@nombre", SqlDbType.VarChar, 50).Value = jugador.nombre; oCmd.Parameters.Add("@apellido", SqlDbType.VarChar, 50).Value = jugador.apellido; oCmd.Parameters.Add("@direccion", SqlDbType.VarChar, 50).Value = jugador.direccion; oCmd.Parameters.Add("@localidad", SqlDbType.VarChar, 50).Value = jugador.localidad; oCmd.Parameters.Add("@telefono", SqlDbType.VarChar, 50).Value = jugador.telefono; oCmd.Parameters.Add("@telCelular", SqlDbType.VarChar, 50).Value = jugador.telCelular; oCmd.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = jugador.email; oCmd.Parameters.Add("@fechaNacimiento", SqlDbType.Date, 50).Value = jugador.fechaNacimiento; oCmd.Parameters.Add("@eloLocal", SqlDbType.VarChar, 50).Value = jugador.eloLocal; oCmd.Parameters.Add("@idFide", SqlDbType.VarChar, 50).Value = jugador.idFide; oCmd.Parameters.Add("@sexo", SqlDbType.VarChar, 50).Value = jugador.sexo; oCmd.Parameters.Add("@idInstitucion", SqlDbType.Int).Value = jugador.idInstitucion; oCmd.Parameters.Add("@baja", SqlDbType.Bit).Value = jugador.baja; //Ejecutamos el comando oCmd.ExecuteNonQuery(); } } } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al actualizar datos del jugador.", Ex); throw ExcepcionManejada; } }
/// <summary> /// Agrega un jugador a la base de datos /// </summary> /// <param name="jugador">Un objeto Jugador de clase Entidades</param> /// <returns>Un entero correspondiente al ID del nuevo Jugador agregado</returns> public int Add(Entidades.Jugador jugador) { //Creamos la conexión a utilizar. //Utilizamos la sentencia Using para asegurarnos de cerrar la conexión y liberar el objeto al salir de esta sección de manera automática SqlConnection oCnn = Presentación.Conexion.CrearConexion(); try { using (oCnn) { //Abrimos conexion oCnn.Open(); //Creamos un comando para realizar el alta del jugador en la base de datos SqlCommand oCmd = new SqlCommand(); using (oCmd) { //Asignamos la conexion de trabajo oCmd.Connection = oCnn; //Indicamos la sentencia SQL oCmd.CommandText = "INSERT INTO Jugadores (nroDoc, tipoDoc, nombre, apellido, sexo, direccion, localidad, telefono, telCelular, email, fechaNacimiento, eloLocal, idFide, idInstitucion, baja) VALUES (@nroDoc, @tipoDoc, @nombre, @apellido, @sexo, @direccion, @localidad, @telefono, @telCelular, @email, @fechaNacimiento, @eloLocal, @idFide, @idInstitucion, @baja) SELECT @@identity"; //Asignamos los parámetros oCmd.Parameters.Add("@nroDoc", SqlDbType.VarChar, 50).Value = jugador.nroDoc; oCmd.Parameters.Add("@tipoDoc", SqlDbType.VarChar, 50).Value = jugador.tipoDoc; oCmd.Parameters.Add("@nombre", SqlDbType.VarChar, 50).Value = jugador.nombre; oCmd.Parameters.Add("@apellido", SqlDbType.VarChar, 50).Value = jugador.apellido; oCmd.Parameters.Add("@direccion", SqlDbType.VarChar, 50).Value = jugador.direccion; oCmd.Parameters.Add("@localidad", SqlDbType.VarChar, 50).Value = jugador.localidad; oCmd.Parameters.Add("@telefono", SqlDbType.VarChar, 50).Value = jugador.telefono; oCmd.Parameters.Add("@telCelular", SqlDbType.VarChar, 50).Value = jugador.telCelular; oCmd.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = jugador.email; oCmd.Parameters.Add("@fechaNacimiento", SqlDbType.Date, 50).Value = jugador.fechaNacimiento; oCmd.Parameters.Add("@eloLocal", SqlDbType.VarChar, 50).Value = jugador.eloLocal; oCmd.Parameters.Add("@idFide", SqlDbType.VarChar, 50).Value = jugador.idFide; oCmd.Parameters.Add("@sexo", SqlDbType.VarChar, 50).Value = jugador.sexo; oCmd.Parameters.Add("@idInstitucion", SqlDbType.Int).Value = jugador.idInstitucion; oCmd.Parameters.Add("@baja", SqlDbType.Bit).Value = 0; //Ejecutamos el comando y retornamos el id generado return(Convert.ToInt32(oCmd.ExecuteScalar())); } } } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al guardar jugador.", Ex); throw ExcepcionManejada; } }
/// <summary> /// Devuelve los datos de un jugador cuyo nombre se pasa por parametro utilizando un procedure /// Al no funcionar el procedure se hace una consulta directa a DB /// </summary> /// <param name="name"></param> /// <returns></returns> public Entidades.Jugador getJugador(string name) { DataBase _db = new DataBase(); OracleDataReader _dataSQL; Entidades.Jugador player = new Entidades.Jugador(); string _sql = ""; try { _sql = $@"SELECT j.FOTO_JUGADOR, j.NOMBRE, j.DIRECCION, j.PUESTO_HAB, j.FECHA_NAC, j.EQUIPO_JUGADOR FROM JUGADOR j WHERE j.NOMBRE LIKE UPPER('%{ name }%')"; _db.startDB(); _db.Sql = _db.DbConnection.CreateCommand(); _db.Sql.CommandType = CommandType.Text; _db.Sql.CommandText = _sql; _dataSQL = _db.selectSQL(); _dataSQL.Read(); player = new Entidades.Jugador { nombre = _dataSQL[1].ToString(), direccion = _dataSQL[2].ToString(), puestoHab = _dataSQL[3].ToString(), fechaNac = (_dataSQL[4] is DBNull) ? DateTime.Now : (DateTime)_dataSQL[4], equipoJugador = _dataSQL[5].ToString() }; } catch (Exception e) { throw new Exception("Error en getJugador(): " + e.Message); } finally { // Llamar siempre a Close una vez finalizada la lectura _db.closeDB(); } return(player); }
private void btnCancelForm_Click(object sender, EventArgs e) { var confirmResult = MessageBox.Show("¿Seguro que desea cancelar la modificación de este jugador?", "Cancelar", MessageBoxButtons.YesNo); if (confirmResult == DialogResult.Yes) { gbDataPlayer.Visible = false; player = new Entidades.Jugador(); tbName.Text = String.Empty; tbAddress.Text = String.Empty; setAvatar(player.avatar); cbTeam.SelectedItem = false; dtFechaNac.Value = DateTime.Now; } }
/// <summary> /// Actualiza un Jugador de la base de datos /// </summary> /// <param name="jugador"></param> /// <remarks></remarks> public void Update(Entidades.Jugador jugador) { //Utiliza la capa de datos para la operación //Si hay alguna validación extra a realizar este es el momento de hacerla Presentación.Jugadores oDatos; try { //Crea una instancia de la clase Jugador de la capa de datos para realizar la operación y delegar la tarea oDatos = new Presentación.Jugadores(); oDatos.Update(jugador); } finally { oDatos = null; } }
private void dgPlayers_CellClick(object sender, DataGridViewCellEventArgs e) { if (dgPlayers.CurrentRow != null) { gbDataPlayer.Visible = true; try { String namePlayer = dgPlayers.CurrentRow.Cells[0].Value.ToString(); player = mundial.getJugador(namePlayer); tbName.Text = player.nombre; tbAddress.Text = player.direccion; tbPuestoHab.Text = player.puestoHab; cbTeam.SelectedItem = player.equipoJugador; dtFechaNac.Value = player.fechaNac; setAvatar(player.avatar); } catch (Exception ex) { MessageBox.Show("Ha ocurrido un error al obtener al usuario: " + ex.Message); } } }
/// <summary> /// Retorna todos los jugadores de una institución de la base de datos /// </summary> /// <returns></returns> public Entidades.Jugadores GetAll(int id) { //Creamos la conexión a utilizar. //Utilizamos la sentencia Using para asegurarnos de cerrar la conexión y liberar el objeto al salir de esta sección de manera automática SqlConnection oCnn = Presentación.Conexion.CrearConexion(); try { using (oCnn) { //Abrimos conexion oCnn.Open(); //Creamos un comando para obtener todos los jugadores de la base de datos SqlCommand oCmd = new SqlCommand(); using (oCmd) { //Asignamos la conexion de trabajo oCmd.Connection = oCnn; //Indicamos la sentencia SQL oCmd.CommandText = "SELECT * FROM Jugadores WHERE idInstitucion = @idInstitucion AND baja = 0"; //Le asignamos el parámetro oCmd.Parameters.Add("@idInstitucion", SqlDbType.Int).Value = id; //Siempre devolvemos una colección. Es más fácil de manipular y controlar Entidades.Jugadores oJugadores = new Entidades.Jugadores(); //No retornamos DataSets, siempre utilizamos objetos para hacernos independientes de la estructura de las tablas en el resto de las capas. //Para esto, leemos con el DataReader y creamos los objetos asociados que se esperan try { //Ejecutamos el comando y retornamos los valores SqlDataReader oReader = oCmd.ExecuteReader(); using (oCnn) { while (oReader.Read()) { //Si existe algun valor, creamos el objeto y lo almacenamos en la colección Entidades.Jugador oJugador = new Entidades.Jugador(); oJugador.idJugador = Convert.ToInt32(oReader["idJugador"]); oJugador.idInstitucion = Convert.ToInt32(oReader["idInstitucion"]); oJugador.apellido = Convert.ToString(oReader["apellido"]); oJugador.nombre = Convert.ToString(oReader["nombre"]); oJugador.direccion = Convert.ToString(oReader["direccion"]); oJugador.localidad = Convert.ToString(oReader["localidad"]); oJugador.telefono = Convert.ToString(oReader["telefono"]); oJugador.telCelular = Convert.ToString(oReader["telCelular"]); oJugador.email = Convert.ToString(oReader["email"]); oJugador.nroDoc = Convert.ToString(oReader["nroDoc"]); oJugador.tipoDoc = Convert.ToString(oReader["tipoDoc"]); oJugador.fechaNacimiento = Convert.ToDateTime(oReader["fechaNacimiento"]); oJugador.idFide = Convert.ToString(oReader["idFide"]); oJugador.eloLocal = Convert.ToString(oReader["eloLocal"]); oJugador.sexo = Convert.ToString(oReader["sexo"]); oJugador.baja = Convert.ToInt32(oReader["baja"]); //Agregamos el objeto a la coleccion de resultados oJugadores.Add(oJugador); oJugador = null; } //Retornamos los valores encontrados return(oJugadores); } } finally { //El Finally nos da siempre la oportunidad de liberar la memoria utilizada por los objetos oJugadores = null; } } } } catch (Exception Ex) { Exception ExcepcionManejada = new Exception("Error al obtener los datos de los jugadores.", Ex); throw ExcepcionManejada; } }
/* * NO FUNCIONA EL PROCEDURE, DEVUELVE SIEMPRE NULL * public DataTable getJugador(string name) * { * DataBase _db = new DataBase(); * OracleDataAdapter _adapter; * DataTable dtJugador = new DataTable(); * * try * { * _db.startDB(); * _db.Sql = _db.DbConnection.CreateCommand(); * _db.Sql.BindByName = true; * _db.Sql.CommandType = CommandType.StoredProcedure; * _db.Sql.CommandText = "CONSULTAS.OBTENER_JUGADOR"; * _db.Sql.Parameters.Add("v_nombre", OracleDbType.Varchar2, name, ParameterDirection.Input); * _db.Sql.Parameters.Add("est_jugador", OracleDbType.RefCursor, DBNull.Value, ParameterDirection.Output); * _db.Sql.Parameters.Add("C2BLOB", OracleDbType.Blob, DBNull.Value, ParameterDirection.Output); * _adapter = new OracleDataAdapter(_db.Sql); * _adapter.Fill(dtJugador); * * } * catch (Exception e) * { * throw new Exception("Error en getJugador(): " + e.Message); * } * finally * { * // Llamar siempre a Close una vez finalizada la lectura * _db.closeDB(); * } * return dtJugador; * }*/ /// <summary> /// Recupera un listado de jugadores según los parámetros que se le envíen /// </summary> /// <param name="_name"></param> /// <param name="_team"></param> /// <param name="_year"></param> /// <returns></returns> public List <Entidades.Jugador> getJugadores(string _name, string _team, int?_year) { DataBase _db = new DataBase(); OracleDataReader _dataSQL; List <Entidades.Jugador> listJugadores = new List <Entidades.Jugador>(); string _sql = ""; string _where = ""; try { if (_name != null && _name != String.Empty) { _where = (_where.Equals(String.Empty)) ? " WHERE " : " AND "; _where += $@"j.NOMBRE LIKE UPPER('%{ _name }%')"; } if (_team != null && _team != String.Empty) { _where = (_where.Equals(String.Empty)) ? " WHERE " : " AND "; _where += $@"e.EQUIPO LIKE UPPER('%{ _team }%')"; } if (_year != null && _year > 0 && _year != DateTime.Now.Year) { _where = (_where.Equals(String.Empty)) ? " WHERE " : " AND "; _where += $@"TO_CHAR(p.FECHA, 'yyyy') = '{ _year }'"; } _sql = $@"SELECT j.FOTO_JUGADOR, j.NOMBRE, j.DIRECCION, j.PUESTO_HAB, j.FECHA_NAC, j.EQUIPO_JUGADOR FROM JUGADOR j WHERE j.NOMBRE IN ( SELECT j2.NOMBRE FROM JUGADOR j2 LEFT JOIN EQUIPOS e ON e.EQUIPO = j2.EQUIPO_JUGADOR LEFT JOIN JUGAR ju ON ju.NOMBRE_JUG = j2.NOMBRE LEFT JOIN PARTIDO p ON ( ju.EQUIPO_L_PART = p.EQUIPO_L OR ju.EQUIPO_V_PART = p.EQUIPO_V ) { _where } GROUP BY j2.NOMBRE) ORDER BY j.NOMBRE"; _db.startDB(); _db.Sql = _db.DbConnection.CreateCommand(); _db.Sql.CommandType = CommandType.Text; _db.Sql.CommandText = _sql; _dataSQL = _db.selectSQL(); while (_dataSQL.Read()) { Entidades.Jugador jugador = new Entidades.Jugador { nombre = _dataSQL[1].ToString(), direccion = _dataSQL[2].ToString(), puestoHab = _dataSQL[3].ToString(), fechaNac = (_dataSQL[4] is DBNull) ? DateTime.Now : (DateTime)_dataSQL[4], equipoJugador = _dataSQL[5].ToString() }; jugador.avatar = ((_dataSQL[0] is DBNull) ? null : (byte[])_dataSQL[0]); listJugadores.Add(jugador); } } catch (Exception e) { throw new Exception("Error en getJugador(): " + e.Message); } finally { // Llamar siempre a Close una vez finalizada la lectura _db.closeDB(); } return(listJugadores); }