SQL query to check free rooms with PreparedStatement in Java

3

I have this query that I pass it to @raintrooper, in this other query that I did How to check if a room is available? :

declare @Vfechaentrada date, @Vfechasalida date

declare @reservaciones table (
habitacion int,
fechaentrada date,
fechasalida date
)

select @Vfechaentrada=getdate() , @Vfechasalida=DATEADD (day , 4 , GETDATE() ) 

insert into @reservaciones
(habitacion,fechaentrada,fechasalida)
select 101,@Vfechaentrada,@Vfechasalida

--intentar reservar el 14 de diciembre

declare @fecha   date='14/12/2017'

select COUNT(1) as libre from @reservaciones where @fecha between  @Vfechaentrada and @Vfechasalida

How can I use placeholders of PreparedStatement in Java with this query? ..

Thank you.

These are the data that I will use:

 Tabla T_Reserva

fechaLlegada: Date
numNoches: integer
numAdultos: integer
numMenDos: integer
numMenDosDoce: integer
TarjetaCrédito
Cliente
TipoHabitación
Tarifa
Reserva
Hotel
localizador: String
observaciones: String
precio: Double
régimen: String
codCliente: String
codHotel: String
tipoHab: String
Clave primaria: localizador
Clave foránea hacia T_Cliente codCliente
Clave foránea hacia T_Hotel codHotel
Clave foránea hacia T_TipHab tipoHab, codHotel
Clave foránea hacia T_Tarifa fechaLlegada, regimen, tipoHab, codHotel
Como clave primaria alternativa tenemos, codigoHotel, codigoCliente,
FechaLlegada, pero de esta manera sólo puede haber un reserva para un cliente en
una fecha determinada.

Tabla T_Cliente

codCliente: String
nombre: String
apellido: String
dirección: String
provincia: String
país: String
código postal: String
teléfono: String
móvil: String
email: String
Clave primaria: codCliente
Tabla T_TarCre
número: String
caducidad: String
tipo: String
codCliente: String
Clave primaria: número
Clave foránea hacia T_Cliente codCliente

Tabla T_Hotel

codigoHotel: String
Nombre: String
fechaMaxEntrada: Date
numMaxNoches : integer
Clave primaria: codHotel 



Tabla T_TipHab

tipo: String
numMáxPersonas: integer
disponibilidad: integer
codHotel: String
precio: real
Clave primaria: tipo, codHotel
Clave foránea hacia T_Hotel codHotel

Tabla T_Tarifa

precioNoche: Double
fechaInicio: Date
fechaFin: Date
regimen: String
tarifa: Double
codHotel: String
tipoHab: String
Clave primaria: fechaInicio, regimen, tipoHab, codHotel,
Clave foránea hacia T_TipHab tipoHab, codHotel
    
asked by TOMAS 13.12.2017 в 11:28
source

2 answers

2

That query is a proof of concept, so I assume you'll want to use it in production in real tables. You should use something similar to this:

/* La conexión la tenemos definida en "con" */
PreparedStatement busquedaStmt = null;
String busquedaString = "SELECT COUNT(*) libre " +
  "FROM reservas " +
  "WHERE habitacion = ? AND ? BETWEEN fechaentrada AND fechasalida";
try {
  /* Si sólo queremos consultar la disponibilidad pero aún no
     queremos hacer efectiva la reserva no necesitamos una transacción */
  con.setAutoCommit(true);
  busquedaStmt = con.prepareStatement(busquedaString);
  /* Asignamos las variables a los "?" de la consulta SQL */
  busquedaStmt.setInt(1, habitacion);
  busquedaStmt.setString(2, fecha);
  /* Ejecutamos la consulta */
  ResultSet rs = busquedaStmt.executeQuery();
  while (rs.next()) {
    /* Obtenemos el único campo del único resultado */
    int libre = rs.getInt("libre");
    /* Hacemos lo que tengamos que hacer con el resultado */
    /* ... */
  }
} catch (SQLException e) {
  /* ... */
} finally {
  /* ... */
}
    
answered by 13.12.2017 / 11:43
source
2

As well OscarGarcia responded with respect to the java code you can base yourself on that form of programming, then to pay to the solution if you have more questions you can check this link that I created link , in it you can make sql queries online and share them, besides you already have the database schema according to the example you present.

As a recommendation you must add in the SQL the number of the room you want to consult otherwise when you want to look for a reservation for room 1 the SQL will look for instances for any room with the following data, for example.

INSERT INTO 'reservaciones' ('habitacion', 'fechaentrada', 'fechasalida') 
VALUES
('1', '2017-12-14', '2017-12-18'),
('1', '2017-12-19', '2017-12-21'),
('2', '2017-12-14', '2017-12-15'),
('3', '2017-12-14', '2017-12-15');

Select count(*) from reservaciones where '2017-12-15' BETWEEN fechaentrada 
AND fechasalida; -- dará come resultado 3

Select count(*) from reservaciones where habitacion = 1 AND '2017-12-15' 
BETWEEN fechaentrada AND fechasalida; -- dará como resultado 1

en java seria: SELECT COUNT(*) libre FROM reservas WHERE habitacion = ? AND ? BETWEEN fechaentrada AND fechasalida; -- tener en cuenta que el segundo ? debe ser un tipo de dato Date en java. 

all this you can experience online with the link that I have previously placed and so it will be easier to raise new questions in the future.

    
answered by 13.12.2017 в 13:10