[ Foro de C# ]

ejercicio 10.8.3

14-May-2016 02:46
Invitado (Cristian)
1 Respuestas

hola saludos, bueno soy nuevo en el foro, estoy leyendo el pdf de c# y quería  preguntarles acerca del ejercicio 10.8.3, mi duda es como  puedo exportar los datos guardado en la BD a un  archivo de texto y viceversa el ejercicio dice:

(10.8.3) Amplía el ejemplo 10.8.2, para que permita exportar los datos a un fichero de texto (que contenga el nombre, la dirección y la edad correspondientes a cada registro en líneas separados), o bien se pueda importar datos desde un fichero de texto (añadiendo al final de los existentes).

y el código que crea la bd y agrega datos es algo así


using System;
using System.IO;
using System.Data;
using System.Data.SQLite;

namespace BasedeDatosP
{
	class AgendaSQLite
	{
		static SQLiteConnection conexion;

		public AgendaSQLite()
		{
			AbrirBD ();
		}

		private void AbrirBD()
		{
			if (!File.Exists ("agenda.sqlite")) {
				conexion = new SQLiteConnection ("Data Source=agenda.sqlite;Version=3;New=True;Compress=True");
				conexion.Open ();

				string creacion = "create table persona" +
				                  "(Nombre varchar (30), Direccion varchar (30) , Edad int);";
				SQLiteCommand cmd = new SQLiteCommand (creacion, conexion);
				cmd.ExecuteNonQuery ();

			} 

			else 
				
			{
				conexion = new SQLiteConnection ("Data Source=agenda.sqlite;Version=3;New=False;Compress=True");
				conexion.Open ();
			}

		}


		public bool insertarDatos(string Nombre, string Direccion, int edad)
		{
			string insercion;
			SQLiteCommand cmd;
			int cantidad;
			try
			{
			insercion = "insert into persona values ('"+Nombre+"','"+Direccion+"', '"+edad+"');";
			cmd = new SQLiteCommand (insercion, conexion);
			cantidad = cmd.ExecuteNonQuery ();
			if (cantidad < 1)
				return false;
			}
			catch(Exception e)
			{
				Console.WriteLine ("ha habido un error {0}", e.Message);
				return false;
			}
			return true;
		}

		public string LeerDatos()
		{
			string consulta = "select * from persona;";
			string resultado = "";

			SQLiteCommand cmd = new SQLiteCommand (consulta, conexion);
			SQLiteDataReader datos = cmd.ExecuteReader ();

			while (datos.Read ()) 
			{
				resultado += Convert.ToString (datos [0]) + " - " + Convert.ToString (datos [1]) + " - " + Convert.ToInt32 (datos [2]) + "\n"; 
			}
			return resultado;

		}

		public string LeerBusqueda(string texto)
		{
			string consulta = "select * from persona where Nombre like '%"+texto+"%' or Direccion like '%"+texto+"%';";
			string resultado = "";

			SQLiteCommand cmd = new SQLiteCommand (consulta, conexion);
			SQLiteDataReader datos = cmd.ExecuteReader ();

			while (datos.Read ())
			{
				resultado += Convert.ToString(datos [0]) + " - " + Convert.ToString(datos [1]) + " - " + Convert.ToInt32(datos [2]) + "\n";
			}

			return resultado;
		}

		public bool BorrarDato(string texto)
		{
			string consulta = "delete from persona where Nombre like '"+texto+"';";
			int cantidad =0 ;

			SQLiteCommand cmd = new SQLiteCommand (consulta, conexion);
			cantidad =cmd.ExecuteNonQuery ();
			if (cantidad < 1)
				return false;
			
			return true;
		}

		public bool ModificarDato(string texto, string textoModificado)
		{
			string consulta = "update persona set Nombre ='"+textoModificado+"' where Nombre='"+texto+"';";
			int cantidad  = 0 ;

			SQLiteCommand cmd = new SQLiteCommand (consulta, conexion);
			cantidad = cmd.ExecuteNonQuery ();

			if (cantidad < 1)
				return false;

			return true;

		}

		~AgendaSQLite()
		{
			conexion.Close ();
		}


	}

	public class Prueba
	{
		public static void Main()
			{
			AgendaSQLite agenda = new AgendaSQLite ();
			string opcion;

			do {
				Console.WriteLine ("Escoja una opcion");
				Console.WriteLine ("1.--Añadir Datos");
				Console.WriteLine ("2.--Mostrar Datos");
				Console.WriteLine ("3.--Buscar");
				Console.WriteLine ("4.--Borrar dato");
				Console.WriteLine ("5.--Modificar dato");
				Console.WriteLine ("0.--salir");
				opcion = Console.ReadLine ();

				switch (opcion) {
				case "1":
					Console.WriteLine ("Nombre?");
					string n = Console.ReadLine ();
					Console.WriteLine ("Direccion?");
					string d = Console.ReadLine ();
					Console.WriteLine ("Edad?");
					int e = Convert.ToInt32 (Console.ReadLine ());

					agenda.insertarDatos (n, d, e);
					break;

				case "2":
					Console.WriteLine (agenda.LeerDatos ());
					break;

				case "3":
					Console.WriteLine ("Texto a buscar?");
					string txt = Console.ReadLine ();
					Console.WriteLine (agenda.LeerBusqueda(txt));
					break;

				case "4":
					Console.WriteLine("Nombre de la persona");
					string borrar = Console.ReadLine();
					Console.WriteLine(agenda.BorrarDato(borrar));
					break;
				case "5":
					Console.WriteLine("texto a Modificar");
					string modi = Console.ReadLine();
					Console.WriteLine("nuevo Texto");
					string nuevotxt = Console.ReadLine();
					Console.WriteLine(agenda.ModificarDato(modi,nuevotxt));
					break;
				}
				
			} while(opcion != "0");


			
			}


	}
}


 


20-May-2016 23:25
Nacho Cabanes (+84)

Si sabes mostrar los datos en pantalla y has manejado ficheros, deberías poder volcar con facilidad a un fichero de texto: bastaría con un "fichero.WriteLine" para cada campo.






(No se puede continuar esta discusión porque tiene más de dos meses de antigüedad. Si tienes dudas parecidas, abre un nuevo hilo.)