public void TestExecuteReader() { using (var db = new SQLDBConnection("sqlite", "", "", ":memory:")) { db.Open(); try { db.Transaction((t) => { t.ExecuteNonQuery("CREATE TABLE test(i INTEGER)"); t.ExecuteNonQuery("INSERT INTO test VALUES(:V)", DbParam.New("V", 1)); }); } catch (Exception) { } var i = 0; db.ExecuteReader(@"SELECT * FROM test WHERE i=:V", (rd) => { i++; return(true); }, DbParam.New("V", 1)); if (i != 1) { throw new Exception("Data read not successfull"); } db.Close(); }; }
public static void InsertRoom(SQLDBConnection myDB) { int result; //Para los resultados de las consultas RUDI bool exit; DataTable dTable; Console.WriteLine($"REGISTRANDO HABITACION"); do { string strAvailable, roomNumber; Console.Write("Room Number: "); roomNumber = Console.ReadLine(); Console.Write("Disponibilidad: "); strAvailable = Console.ReadLine(); if (strAvailable == "0" || strAvailable == "1") { result = RUDI.Insert(myDB, "Rooms", "RoomNumber, Available", $"{roomNumber},{strAvailable}"); if (result == 1) { int roomID; dTable = RUDI.Read(myDB, "Rooms", "RoomID", $"RoomNumber = {roomNumber}"); //SELECT RoomID FROM Rooms WHERE RoomNumber = roomNumber roomID = Convert.ToInt32(dTable.Rows[0]["RoomID"]); Console.WriteLine($"La Habitación {roomNumber} ha sido añadida con exito bajo el ID#: {roomID}", Color.Blue); Menu.WriteContinue(); } exit = false; } else { exit = true; } } while (false); }
public void TestReadSingleRow() { using (var db = new SQLDBConnection("sqlite", "", "", ":memory:")) { db.Transaction((t) => { try{ t.ExecuteNonQuery("DROP TABLE test"); }catch (Exception) {} t.ExecuteNonQuery("CREATE TABLE test(i INTEGER,d REAL, dt DATETIME)"); t.ExecuteNonQuery("INSERT INTO test VALUES(:I,:F,:DT)", DbParam.New("I", 1), DbParam.New("F", 123.456), DbParam.New("DT", DateTime.Now)); }); var v = db.ReadVector <long>("SELECT i FROM test"); if (v[0] != 1) { throw new Exception("Data read not successfull"); } var d = db.ReadOneDouble("SELECT d FROM test"); if (d != 123.456) { throw new Exception("Data read not successfull"); } var dt = db.ReadOneDateTime("SELECT dt FROM test"); if (dt == null) { throw new Exception("Data read not successfull"); } }; }
public static bool RentMovie(SQLDBConnection myDB, Client cWillRent, int ID_Movie, DateTime c_In, DateTime c_Out) { Console.WriteLine($"\nPROCESANDO ALQUILER DE PELICULA DISPONIBLE\n"); HpVarious.ShowProgressBar(10, 100); //var table = new ConsoleTable("ID", "Title", "Synopsis"); if (CanCLientRentTheMovie(myDB, ID_Movie, cWillRent)) //Si existe la peli y si esta disponible { if (RUDI.Insert(myDB, "Rented", "ID_Client, ID_Movie, C_In, C_Out", $"{cWillRent.ID_Client}, {ID_Movie}, '{c_In.ToString("MM/dd/yyyy")}', '{c_Out.ToString("MM/dd/yyyy")}'") == 1) //Es porque actualizó { //UPDATE campo State of This Movie if (RUDI.Update(myDB, "Movies", "State=0", $"ID_Movie={ID_Movie}") == 1) { DataTable dTable = RUDI.Read(myDB, "Rented", "ID_Rented", $"ID_Movie={ID_Movie} AND ID_Client={cWillRent.ID_Client}"); Console.WriteLine($"\nEl alquiler se ha procesado con éxito, bajo el ID: {dTable.Rows[0].Field<int>(0)}", Color.Blue); Menu.WriteContinue(); return(true); } } return(false); } else { Console.WriteLine("Error. Pelicula no Disponible o No tiene la edad suficiente para alquilar la pelicula", Color.DarkRed); Console.ResetColor(); } Menu.WriteContinue(); return(false); }
public void TestDBException() { var s = ""; using (var db = new SQLDBConnection("sqlite", "", "", ":memory:")) { db.Open(); try { var SQL = "SELECT * FROM NotExistedTable"; db.ExecuteReader(SQL, (rd) => { return(true); }); }catch (Exception ex) { s = ex.Message; } db.Close(); }; if (s == "") { throw new Exception("Exception was not generated in ExecuteReader"); } }
public static bool DeleteMovie(SQLDBConnection myDB, Client clientForRemoveMovie, int ID_Movie) { Console.WriteLine($"\nPROCESANDO DEVOLUCIÓN DE PELICULA\n"); HpVarious.ShowProgressBar(10, 100); //var table = new ConsoleTable("ID", "Title", "Synopsis"); if (CanMovieBeRemove(myDB, ID_Movie)) //Si existe la peli y si No esta disponible, es que esta alquilada y puede ser removida { if (RUDI.Delete(myDB, "Rented", $"ID_Movie = {ID_Movie}") == 1) { //UPDATE campo State of This Movie if (RUDI.Update(myDB, "Movies", "State=1", $"ID_Movie={ID_Movie}") == 1) { DataTable dTable = RUDI.Read(myDB, "Rented", "ID_Rented", $"ID_Movie={ID_Movie} AND ID_Client={clientForRemoveMovie.ID_Client}"); Console.WriteLine($"\nLa pelicula bajo el ID: {ID_Movie} ha sido removida con exito, ahora se encuentra disponible", Color.Blue); Menu.WriteContinue(); return(true); } } return(false); } else { Console.WriteLine("Error. No existe la pelicula o no ha sido alquilada bajo su usuario", Color.Red); } Menu.WriteContinue(); return(false); }
public void TestSelectOutOfTransactionSQLite() { using (var db = new SQLDBConnection(SQLiteTestConnection)) { db.Open(); db.Transaction((th) => { try { th.ExecuteNonQuery("DROP TABLE test"); } catch (Exception) { }; }); db.Transaction((th) => { th.ExecuteNonQuery("CREATE TABLE test(i INTEGER)"); th.ExecuteNonQuery("INSERT INTO test(i) VALUES(1)"); }); db.ExecuteReader("SELECT i FROM test", (rd) => { db.Transaction((th) => { th.ExecuteNonQuery("UPDATE test SET i=2 WHERE i=1"); //db.ExecuteReader("SELECT i FROM test", (rd) => //{ // return true; //}); }); return(true); }); db.Transaction((th) => { th.ExecuteNonQuery("DROP TABLE test"); }); db.Close(); }; }
public void TestMultiTransactionsSQLite() { using (var db = new SQLDBConnection(SQLiteTestConnection)) { db.Open(); db.Open(); db.Transaction((th) => { try { th.ExecuteNonQuery("DROP TABLE test"); } catch (Exception) { }; }); db.Transaction((th) => { try { th.ExecuteNonQuery("DROP TABLE test2"); } catch (Exception) { }; }); db.Transaction((th) => { th.ExecuteNonQuery("CREATE TABLE test(i INTEGER)"); th.ExecuteNonQuery("INSERT INTO test(i) VALUES(1)"); var v = db.ReadOneInt("SELECT COUNT(*) FROM test"); // Test Reader executed in transaction context db.Transaction((th) => { th.ExecuteNonQuery("CREATE TABLE test2(i INTEGER)"); th.ExecuteNonQuery("INSERT INTO test2(i) VALUES(1)"); th.ExecuteNonQuery("DROP TABLE test2"); }); th.ExecuteNonQuery("DROP TABLE test"); }); db.Close(); }; }
public void TestNestedReaderSQLite() { using (var db = new SQLDBConnection(SQLiteTestConnection)) { db.Open(); try { db.Transaction((t) => { try { t.ExecuteNonQuery("DROP TABLE test"); } catch (Exception) { } }); db.Transaction((t) => { t.ExecuteNonQuery("CREATE TABLE test(i INTEGER)"); t.ExecuteNonQuery("INSERT INTO test VALUES(:V)", DbParam.New("V", 1)); }); } catch (Exception) { } var i = 0; db.ExecuteReader("SELECT * FROM test WHERE i=:V", (rd) => { db.ExecuteReader("SELECT * FROM test", (rd) => { return(true); }); i++; return(true); }, DbParam.New("V", 1)); if (i != 1) { throw new Exception("Data read not successfull"); } }; }
public void TestSqliteConnection() { using (var db = new SQLDBConnection(SQLiteTestConnection)) { db.Open(); db.Close(); }; }
public DbTests() { db = new SQLDBConnection("sqlite", "", "", ":memory:"); db.Transaction(th => { th.ExecuteNonQuery("CREATE TABLE test(c1 INTEGER,c2 INTEGER, c3 INTEGER)"); th.ExecuteNonQuery("INSERT INTO test VALUES(11,12,13)"); th.ExecuteNonQuery("INSERT INTO test VALUES(21,22,23)"); th.ExecuteNonQuery("INSERT INTO test VALUES(31,32,33)"); }); }
public void TestExecuteNonQuery() { using (var db = new SQLDBConnection("sqlite", "", "", ":memory:")) { db.Open(); db.Transaction((t) => { try{ t.ExecuteNonQuery("CREATE TABLE test(i INTEGER)"); }catch (Exception) {} t.ExecuteNonQuery("INSERT INTO test VALUES(:V)", DbParam.New("V", 1)); }); db.Close(); }; }
// Si la pelicula existe, esta disponible y el cliente tiene la edad suficiente devolverá true public static bool CanCLientRentTheMovie(SQLDBConnection myDB, int ID_Movie, Client cWillRent) { DataTable dTable; if (MovieExist(myDB, ID_Movie)) { dTable = RUDI.Read(myDB, "Movies", "ID_Movie", $"ID_Movie = {ID_Movie} AND State = 1 AND RecommendedAge <= {HpVarious.GetAges(cWillRent.Birthdate)}"); //SELECT ClientID FROM Clients WHERE DNI = strDNI if (dTable != null && dTable.Rows.Count > 0) { return(true); } } return(false); }
public static bool CanMovieBeRemove(SQLDBConnection myDB, int ID_Movie) { DataTable dTable; if (MovieExist(myDB, ID_Movie)) { dTable = RUDI.Read(myDB, "Movies", "ID_Movie", $"ID_Movie = {ID_Movie} AND State = 0"); //SELECT ClientID FROM Clients WHERE DNI = strDNI if (dTable != null && dTable.Rows.Count > 0) { return(true); } } return(false); }
public static bool BookExist(SQLDBConnection myDB, int intBookingID) { DataTable dTable; if (intBookingID > 0) { dTable = RUDI.Read(myDB, "Bookings", "BookingID", $"BookinID={intBookingID}"); //SELECT BookingID FROM Bookings WHERE BookinID = intBookingID if (dTable != null && dTable.Rows.Count > 0) { return(true); } } return(false); }
public static bool RoomExist(SQLDBConnection myDB, int intRoomNumber) { DataTable dTable; if (intRoomNumber >= 0) { dTable = RUDI.Read(myDB, "Rooms", "RoomID", $"RoomNumber={intRoomNumber}"); //SELECT RoomID FROM Rooms WHERE RoomID = intRoomID if (dTable != null && dTable.Rows.Count > 0) { return(true); } } return(false); }
// Recibe DNI y busca si el cliente existe en la DB public static bool ClientExist(SQLDBConnection myDB, string strDNI) { DataTable dTable; if (strDNI.Length == 9) { dTable = RUDI.Read(myDB, "Clients", "ClientID", $"DNI LIKE '{strDNI.ToUpper()}'"); //SELECT ClientID FROM Clients WHERE DNI = strDNI if (dTable != null && dTable.Rows.Count > 0) { return(true); } } return(false); }
public static bool ClientEmailExist(SQLDBConnection myDB, int ID_Client) { DataTable dTable; if (ID_Client > 0) { dTable = RUDI.Read(myDB, "Clients", "Name", $"ID_Client={ID_Client}"); //SELECT ClientID FROM Clients WHERE DNI = strDNI if (dTable != null && dTable.Rows.Count > 0) { return(true); } } return(false); }
public static bool ClientPasswordExist(SQLDBConnection myDB, string[] userAndPass) { DataTable dTable; if (userAndPass[0].Length == 9) { dTable = RUDI.Read(myDB, "Clients", "email", $"DNI LIKE '{userAndPass[0].ToUpper()}' AND pass LIKE '{userAndPass[1].ToLower()}'"); //SELECT ClientID FROM Clients WHERE DNI = strDNI if (dTable != null && dTable.Rows.Count > 0) { return(true); } } return(false); }
public void TestOdbcConnection() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "."; var fname = Path.GetFullPath(Path.Combine(location, "..", "..", "..", "TestData", "MWCONFIG.MDB")); using (var db = new SQLDBConnection("odbc", "", "", @"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + fname)) { //db.Open(); //db.Close(); }; }
//Si includeStatus = 1 se construye la query con el status = 1, las pelis disponibles //includeStatus = 0 se construye la query con el status = 0, las pelis NO disponibles //includeStatus = 2 se construye la query sin considerar status, las pelis disponibles y No disponibles public static void ShowMoviesInTableRentedByClient(SQLDBConnection myDB, Client cToCompare) { DataTable dTable; Console.ResetColor(); Console.WriteLine($"\nMOSTRANDO TUS PELICULAS ALQUILADAS\n"); HpVarious.ShowProgressBar(10, 100); var table = new ConsoleTable("ID", "Title", "Fecha Alquilada", "Fecha Devolucion", "Tiempo de Entrega"); // SELECT M.Title FROM Clients C, Rented R, Movies M WHERE C.ID_Client = 1 AND R.ID_Client = 1 AND M.ID_Movie = R.ID_Movie dTable = RUDI.Read(myDB, "Clients C, Rented R, Movies M", $"R.ID_Movie, M.Title, R.C_In, R.C_Out", $"C.ID_Client = {cToCompare.ID_Client} AND R.ID_Client = {cToCompare.ID_Client} AND M.ID_Movie = R.ID_Movie"); dTable.Columns.Add("Caducado", typeof(String)); if (dTable != null && dTable.Rows.Count > 0) { foreach (DataRow dataRow in dTable.Rows) { string[] strInfoToPrint = new string[5]; int i = 0; foreach (var item in dataRow.ItemArray) { if (i < 2) { strInfoToPrint[i++] = item.ToString(); } else if (i == 4) { if (Convert.ToDateTime(strInfoToPrint[3]) < DateTime.Today) { strInfoToPrint[i++] = "Caducado"; } else { strInfoToPrint[i++] = "En Plazo"; } } else { strInfoToPrint[i++] = item.ToString().Substring(0, 10);; } } table.AddRow(strInfoToPrint); } } Console.ResetColor(); table.Write(); }
public static void ShowNotBookedRoomInTable(SQLDBConnection myDB, DateTime[] checkIN_OUT) { DataTable dTable; var table = new ConsoleTable("# HABITACIÓN"); Console.WriteLine($"\nHABITACIONES DISPONIBLES PARA LA FECHA INDICADA"); dTable = RUDI.ReadFromSP(myDB, "AvailableRoomsNumber", checkIN_OUT); //AvailableRooms nombre de Proceso Almacenado if (dTable != null && dTable.Rows.Count > 0) { foreach (DataRow row in dTable.Rows) { table.AddRow(row.Field <int>(1)); } } table.Write(); }
public static bool IsTheRoomAvailable(SQLDBConnection myDB, string strDNI) //TODO: Revisar aqui, hay que hacer este metodo { DataTable dTable; if (strDNI.Length == 9) { if (HpClients.ClientExist(myDB, strDNI)) { } dTable = RUDI.Read(myDB, "Clients", "ClientID", $"DNI LIKE '{strDNI.ToUpper()}'"); //SELECT ClientID FROM Clients WHERE DNI = strDNI if (dTable != null && dTable.Rows.Count > 0) { return(true); } } return(false); }
// Muestra las habitaciones disponibles según Fecha Indicada en el array checkIN_OUT public static void ShowNotBookedRoom(SQLDBConnection myDB, DateTime[] checkIN_OUT) { DataTable dTable; Console.WriteLine($"\nHABITACIONES DISPONIBLES PARA LA FECHA INDICADA"); string[] availableRoom = new string[] { "HAB-0", "HAB-" }; dTable = RUDI.ReadFromSP(myDB, "AvailableRoomsNumber", checkIN_OUT); //AvailableRooms nombre de Proceso Almacenado if (dTable != null && dTable.Rows.Count > 0) { foreach (DataRow row in dTable.Rows) { // ... Escribir valor del primer Field como entero. En la pos(0) tengo los RoomID Console.WriteLine($"{availableRoom[1]}{row.Field<int>(1)}"); } } }
public static Client AskNewUserData(SQLDBConnection myDB) { Client clientToInsert = new Client(); do { Console.Write("DNI: "); clientToInsert.DNI = Console.ReadLine().ToUpper(); if (clientToInsert.DNI != "0" && clientToInsert.DNI.Length == 9 /*&& !HpClients.ClientExist(myDB, clientToInsert.DNI)*/) { break; } else { if (clientToInsert.DNI == "0") { Console.WriteLine("ERROR -> El DNI del cliente no puede ser Cero (0)", Color.Red); } else if (clientToInsert.DNI.Length != 9) { Console.WriteLine("ERROR -> El DNI del cliente debe contener 9 caracteres", Color.Red); } else { Console.WriteLine("ERROR -> El cliente Ya existe en la BD. Intente con otro DNI", Color.Red); Menu.WriteContinue(); } } } while (true); //TODO: Este If se puede eliminar, ya que si llega aqui es porque evaluó esta condicion en el While if (clientToInsert.DNI != "0" && clientToInsert.DNI.Length == 9 && !HpClients.ClientExist(myDB, clientToInsert.DNI)) { Console.Write("Name: "); clientToInsert.Name = Console.ReadLine(); Console.Write("Last Name: "); clientToInsert.LastName = Console.ReadLine(); Console.Write("BirtDate: "); clientToInsert.Birthdate = DateTime.Parse(Console.ReadLine()); Console.Write("email: "); clientToInsert.email = Console.ReadLine(); Console.Write("Password: "); clientToInsert.pass = Console.ReadLine(); } return(clientToInsert); }
//Mostrar clientes de la DB // availability = 0 = FALSE, muestra las habitaciones NO disponibles // availability = 1 = TRUE, muestra las habitaciones SI disponibles // availability = 2 , muestra todas las habitaciones, disponibles y no disponibles public static void ShowRoomsInTable(SQLDBConnection myDB, int availability) { DataTable dTable; string disponibles = "DISPONIBLES"; var table = new ConsoleTable("ID", "NUMERO HABITACIÓN", "DISPONIBLE"); if (availability < 0 && availability > 2) { availability = 2; } if (availability == 0) { disponibles = "NO DISPONIBLES"; } else if (availability == 2) { disponibles = "Y SU ESTATUS"; } Console.WriteLine($"MOSTRANDO TODAS LAS HABITACIONES {disponibles}"); if (availability <= 1) { dTable = RUDI.Read(myDB, "Rooms", "RoomID, RoomNumber, Available", $"Available = {availability}"); //Mostrar las habitaciones disponibles o las no disponibles } else { dTable = RUDI.Read(myDB, "Rooms", "RoomID, RoomNumber, Available"); // Mostrar todas las habitaciones } if (dTable != null && dTable.Rows.Count > 0) { foreach (DataRow dataRow in dTable.Rows) { string[] strInfoToPrint = new string[3]; int i = 0; foreach (var item in dataRow.ItemArray) { strInfoToPrint[i++] = item.ToString(); } table.AddRow(strInfoToPrint); } } table.Write(); Menu.WriteContinue(); }
//Carga Cliente en la DB public static bool InsertClient(SQLDBConnection myDB, string strDNI) { int result; //Para los resultados de las consultas RUDI DataTable dTable; Console.WriteLine($"REGISTRANDO CLIENTE BAJO EL DNI: {strDNI}"); string strFirstName, strLastName; if (strDNI != "0" && strDNI.Length == 9 && !ClientExist(myDB, strDNI)) { Console.Write("Name: "); strFirstName = Console.ReadLine(); Console.Write("Last Name: "); strLastName = Console.ReadLine(); result = RUDI.Insert(myDB, "Clients", "Name, LastName, DNI", $"'{strFirstName}', '{strLastName}', '{strDNI.ToUpper()}'"); if (result == 1) { int clientID; dTable = RUDI.Read(myDB, "Clients", "ClientID", $"DNI LIKE '{strDNI}'"); //SELECT ClientID FROM Clients WHERE DNI = strDNI clientID = Convert.ToInt32(dTable.Rows[0]["ClientID"]); Console.WriteLine($"El cliente '{strFirstName} {strLastName}' ha sido creado con exito bajo el ID#: {clientID}", Color.Blue); Menu.WriteContinue(); return(true); } return(false); } else { if (strDNI == "0") { Console.WriteLine("ERROR -> El DNI del cliente no puede ser Cero (0)", Color.Red); } else if (strDNI.Length != 9) { Console.WriteLine("ERROR -> El DNI del cliente debe contener 9 caracteres", Color.Red); } else { Console.WriteLine("ERROR -> El cliente Ya existe en la BD. Intente con otro DNI", Color.Red); Menu.WriteContinue(); } } return(false); }
//Carga Cliente en la DB public static bool InsertClient(SQLDBConnection myDB, Client cToInsert) { int result; //Para los resultados de las consultas RUDI DataTable dTable; Console.WriteLine($"REGISTRANDO CLIENTE BAJO EL DNI: {cToInsert.DNI}"); result = RUDI.Insert(myDB, "Clients", "DNI, Name, LastName, BirthDate, email, pass", $"'{cToInsert.DNI}', '{cToInsert.Name}', '{cToInsert.LastName}', '{cToInsert.Birthdate.ToString("MM/dd/yyyy")}', '{cToInsert.email}', '{cToInsert.pass}'"); if (result == 1) { int clientID; dTable = RUDI.Read(myDB, "Clients", "ID_Client", $"DNI LIKE '{cToInsert.DNI}'"); //SELECT ClientID FROM Clients WHERE DNI = strDNI clientID = Convert.ToInt32(dTable.Rows[0]["ID_Client"]); Console.WriteLine($"El cliente '{cToInsert.Name} {cToInsert.LastName}' ha sido creado con exito bajo el ID#: {clientID}", Color.Blue); Menu.WriteContinue(); return(true); } return(false); }
//Mostrar todos los clientes de la DB public static void ShowClients(SQLDBConnection myDB) { DataTable dTable; Console.WriteLine($"MOSTRANDO TODOS LOS CLIENTES"); dTable = RUDI.Read(myDB, "Clients"); if (dTable != null && dTable.Rows.Count > 0) { foreach (DataRow dataRow in dTable.Rows) { foreach (var item in dataRow.ItemArray) { Console.Write($"{item} "); } Console.WriteLine(); } } Console.ReadLine(); }
//Mostrar clientes de la DB // availability = 0 = false, muestra las habitaciones NO disponibles // availability = 1 = false, muestra las habitaciones SI disponibles // availability = 2 , muestra todas las habitaciones, disponibles y no disponibles public static void ShowRooms(SQLDBConnection myDB, int availability) { DataTable dTable; string disponibles = "DISPONIBLES"; if (availability < 0 && availability > 2) { availability = 2; } if (availability == 0) { disponibles = "NO DISPONIBLES"; } else if (availability == 2) { disponibles = "Y SU ESTATUS"; } Console.WriteLine($"MOSTRANDO TODAS LAS HABITACIONES {disponibles}"); if (availability <= 1) { dTable = RUDI.Read(myDB, "Rooms", "RoomNumber, Available", $"Available = {availability}"); //Mostrar las habitaciones disponibles o las no disponibles } else { dTable = RUDI.Read(myDB, "Rooms"); // Mostrar todas las habitaciones } if (dTable != null && dTable.Rows.Count > 0) { foreach (DataRow dataRow in dTable.Rows) { foreach (var item in dataRow.ItemArray) { Console.Write($"{item} "); } Console.WriteLine(); } } Console.ReadLine(); }