Exemple #1
0
        /// <summary>
        /// Metodo que permite modificar un objeto de tipo televisor el cual toma como referencia la "PRIMARY" en este caso es el "CODIGO" para saber
        /// si ese elemento existe en mi base de datos o no y asi pueda modificarlo  , si el elemento no existe en mi base de datos no pasa nada ni tira excepcion
        /// </summary>
        /// <param name="t">televisor a modificar </param>
        /// <returns>true si pudo modificar , false si no pudo y excepcion si falla la conexion </returns>
        public static bool Modificar(Televisor t)
        {
            bool retorno = false;

            SqlConnection conexion = new SqlConnection(Properties.Settings.Default.conexion);
            SqlCommand    comando  = new SqlCommand();


            comando.CommandText = string.Format("UPDATE Televisores SET marca ='{0}',precio = {1},pulgadas = {2},pais='{3}' WHERE codigo={4}", t.marca, t.precio, t.pulgadas, t.pais, t.id); //id no se modifica porque es clave primaria
            comando.CommandType = System.Data.CommandType.Text;
            comando.Connection  = conexion;

            try
            {
                conexion.Open();
                comando.ExecuteNonQuery(); //ejecuta consultas que no van a retornar ningun tipo de resultado
                conexion.Close();
                retorno = true;
            }
            catch (Exception e)
            {
                throw e;
            }

            return(retorno);
        }
Exemple #2
0
        /// <summary>
        /// Metodo que borra un determinado objeto de tipo televisor de la base de datos de la tabla televisores teniendo en cuenta la "PRIMARY KEY"
        /// como referencia a que objeto en especifico borrar , si  no hay un objeto con esa "primary key" es decir que no existe , no pasa nada y no tira excepcion
        /// </summary>
        /// <param name="t">objeto televisor a borrar</param>
        /// <returns>true si pudo borrar , false si no pudo</returns>
        public static bool Borrar(Televisor t)
        {
            bool retorno = false;

            SqlConnection conexion = new SqlConnection(Properties.Settings.Default.conexion);
            SqlCommand    comando  = new SqlCommand();


            comando.CommandText = string.Format("DELETE Televisores WHERE codigo = {0}", t.id); //id no se modifica porque es clave primaria
            comando.CommandType = System.Data.CommandType.Text;
            comando.Connection  = conexion;

            try
            {
                conexion.Open();
                comando.ExecuteNonQuery(); //ejecuta consultas que no van a retornar ningun tipo de resultado
                conexion.Close();
                retorno = true;
            }
            catch (Exception e)
            {
                throw e;
            }

            return(retorno);
        }
Exemple #3
0
        /// <summary>
        /// Metodo que retorna toda la tabla de televisores en una lista de objetos televisor desde la base de datos a programa
        /// </summary>
        /// <returns>lista de televisores</returns>
        public static List <Televisor> TraerTodos()
        {
            List <Televisor> televisores = new List <Televisor>();

            SqlConnection conexion = new SqlConnection(Properties.Settings.Default.conexion);
            SqlCommand    comando  = new SqlCommand();

            comando.CommandText = "SELECT *FROM Televisores";
            comando.CommandType = System.Data.CommandType.Text;
            comando.Connection  = conexion;

            try
            {
                conexion.Open();

                SqlDataReader lector = comando.ExecuteReader();

                while (lector.Read())
                {
                    Televisor tele = new Televisor(lector.GetInt32(0), lector.GetString(1), lector.GetDouble(2), lector.GetInt32(3), lector.GetString(4));
                    televisores.Add(tele);
                }
                conexion.Close();
            }
            catch (Exception e)
            {
                throw e;
            }

            return(televisores);
        }
Exemple #4
0
        /// <summary>
        /// Metodo que se encarga de traer un objeto de tipo televisor desde la base de datos teniendo como referencia un entero
        /// el cual refiere al codigo de ese objeto en especifico
        /// </summary>
        /// <param name="id">codigo del televisor a traer</param>
        /// <returns>televisore que obtenemos de la base de datos</returns>
        public static Televisor TraerUno(int id) //id que va a elegir para obtener
        {
            Televisor tele;

            SqlConnection conexion = new SqlConnection(Properties.Settings.Default.conexion);
            SqlCommand    comando  = new SqlCommand();

            comando.CommandText = string.Format("SELECT *FROM Televisores where codigo = {0}", id); //el *From es porque quiere todos los campos
            comando.CommandType = System.Data.CommandType.Text;
            comando.Connection  = conexion;

            try
            {
                conexion.Open();

                SqlDataReader lector = comando.ExecuteReader();

                lector.Read(); //es importante colocarlo sino no lee nada

                if (lector.HasRows)
                {
                    tele = new Televisor(lector.GetInt32(0), lector.GetString(1), lector.GetDouble(2), lector.GetInt32(3), lector.GetString(4));
                }
                else
                {
                    tele = null;
                }
                conexion.Close();
            }
            catch (Exception e)
            {
                throw e;
            }

            return(tele);
        }
        static void Main(string[] args)
        {
            SqlConnection    conexion    = new SqlConnection(Properties.Settings.Default.conexion);//conexion es la variable que creamos en la configuracion
            SqlCommand       comando     = new SqlCommand();
            List <Televisor> televisores = new List <Televisor>();

            comando.CommandText = "SELECT *FROM Televisores";         //estos dos van de la mano
            comando.CommandType = System.Data.CommandType.Text;

            comando.Connection = conexion; //es una propiedad

            conexion.Open();               //abre conexion

            #region Leo la Base de Datos y obtengo datos

            SqlDataReader lector = comando.ExecuteReader();
            while (lector.Read())
            {
                Console.Write(lector["pais"] + " - ");
                //Console.Write(lector[0] + " - ");

                Televisor tele = new Televisor(lector.GetInt32(0), lector.GetString(1), lector.GetDouble(2), lector.GetInt32(3), lector.GetString(4));//leo lo de la base de datos y lo agrego a la lista de  televisor                                                                                                                                                   //  Televisor tele = new Televisor((int)lector["id"],(string) lector["marca"], (double)lector["precio"], (int)lector["pulgadas"], (string)lector["pais"]);//todos devuelven object , ahora tenemos que castearlo

                televisores.Add(tele);
            }

            conexion.Close();//cierra conexion

            #endregion

            #region SERIALIZO LOS DATOS

            XmlSerializer sr = new XmlSerializer(typeof(List <Televisor>)); // nole pasamos un solo televisr sino la LISTA para que serialize una coleccion de objetos
            XmlTextWriter xw = new XmlTextWriter("Televisor.xml", Encoding.UTF8);
            XmlTextReader xr = new XmlTextReader("Televisor.xml");
            sr.Serialize(xw, televisores);
            xw.Close(); // lo cerramos pa que no pinche

            List <Televisor> listaTelevisorRead;
            listaTelevisorRead = (List <Televisor>)sr.Deserialize(xr);
            xr.Close();

            #endregion

            #region DataTable

            conexion.Open();

            lector = comando.ExecuteReader();                    //genero replica

            DataTable dataTable = new DataTable("Televisor");    //representacion en memoria de una tabal en base de datos

            dataTable.Load(lector);                              //ya lo agrega al data table

            conexion.Close();                                    //volvemos a cerrar

            dataTable.WriteXmlSchema("Televisores_esquema.xml"); //guardamos el esquema
            dataTable.WriteXml("Televisore_dt.xml");             //leemos el esquema

            DataTable dataTable2 = new DataTable();

            dataTable2.ReadXmlSchema("Televisores_esquema.xml");//primero leemos el esquema
            dataTable2.ReadXml("Televisore_dt.xml");

            #endregion

            #region Metodo Insertar

            Televisor telenueva = new Televisor(34, "samsung", 43000, 45, "Estados Unidos");

            Televisor.Borrar(telenueva);

            Console.WriteLine(telenueva.Insertar());

            #endregion

            #region Metodo Modificar

            Televisor teleModificar = new Televisor(7, "philips", 30250, 46, "Inglaterra");
            //Console.WriteLine(teleModificar.Insertar()); //agrego un objeto nuevo a la base de datos
            Televisor.Borrar(teleModificar);
            teleModificar.pais = "POLONIA"; //modifico un parametro

            Console.WriteLine(Televisor.Modificar(teleModificar));

            #endregion

            #region Metodo Borrar

            Televisor teleBorrar = new Televisor(10, "megaman", 100234, 54, "RUSIA");
            //Console.WriteLine(teleBorrar.Insertar()); /// agrego el televisor que voy a borrar

            Console.WriteLine(Televisor.Borrar(teleBorrar)); //borro la television que agregue a mi base de datos

            #endregion

            #region Metodo TraerTodos

            List <Televisor> listaTelevisoresMetodo = Televisor.TraerTodos();

            #endregion

            #region Metodo TraerUno

            Televisor teleTraerUno = Televisor.TraerUno(9);

            #endregion
            Console.ReadKey();
        }