Good morning, I have a problem with a web application I'm creating. Premtto I'm quite new in this kind of programming.
So my web application should take care of booking hotel rooms. My problem is going to make a check when someone tries to book a room, so that you can not book two equal rooms in the same period.
Only that with the code written the check is not performed and the room is still booked. How could I do according to you? Thank you very much for your help.
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "123456789");
out.println("Connect");
Statement st = con.createStatement();
Statement stmt = con.createStatement();
out.println("connection successfull");
String check = ("SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate\n" +
"FROM reservation res1, reservation res2\n" +
"WHERE ( res1.typeroom = res2.typeroom ) \n" +
"AND res1.id_prenotazione != res2.id_prenotazione\n" +
"AND (res1.arrivaldate <= res2.departuredate)\n" +
"AND (res2.arrivaldate <= res1.departuredate)");
// ResultSet rs2 = stmt.executeQuery(check);
out.println("<h1> Stringa chek eseguita </h1>");
if (check) { // THIS DOESN't WORK OF COURSE
int rs = st.executeUpdate("insert into reservation (login,email,typeroom,numroom,arrivaldate,departuredate)values ('" + login + "','" + email + "','" + typeroom + "','" + numroom + "','" + arrivaldate + "','" + departuredate + "')");
}
String getResultSet = ("SELECT count(*) FROM reservation WHERE arrivaldate ='" + arrivaldate + "'");
String rs1 = ("SELECT count(*) FROM reservation WHERE arrivaldate");
if (getResultSet != rs1) {
int i = st.executeUpdate("DELETE FROM reservation WHERE id_prenotazione ='" + id_prenotazione + "'");
}
TABLE reservation (
id_prenotazione int(11) NOT NULL AUTO_INCREMENT,
login varchar(45) NOT NULL,
email varchar(45) NOT NULL,
typeroom varchar(45) NOT NULL,
numroom int(11) NOT NULL,
arrivaldate datetime NOT NULL,
departuredate datetime NOT NULL,
PRIMARY KEY (id_prenotazione)
TABLE users (
login varchar(45) NOT NULL,
firstname varchar(45) NOT NULL,
lastname varchar(45) NOT NULL,
password varchar(45) NOT NULL,
PRIMARY KEY (login)
You are using a join with the same table in your check SELECT but nothing has been inserted yet so the query is pointless. You need to check against the values for the reservation you want to store.
SELECT COUNT(*)
FROM reservation
WHERE numroom = $roomnumber -- I am guessing numroom is room number
AND ($startdate >= arrivaldate AND $startdate <= departuredate)
OR ($enddate >= arrivaldate AND $enddate <= departuredate)
Replace the variables ($...) with your values. You might want to look into how to validate dates against each other, maybe it should be <, > rather than <=, >= in the comparison.
In Java this would be
String query = "SELECT COUNT(*) FROM reservation WHERE numroom = '" + numroom + "' AND ('" + arrivaldate + "' >= arrivaldate AND '" + arrivaldate + "' <= departuredate) OR ('" + departuredate + "' >= arrivaldate AND '" + departuredate + "' <= departuredate)
Related
I'm studying at a project about the creation of simple web application.
I'm creating a webapp about an Hotel and I have a problem about the reservation of a room.
I have 3 kind of rooms and I want when someone book a room, another one can't book the same room in the same period.
The problem is about this kind of control.
I have write this code:
UPDATE CODE AFTER AN ANSWER
Statement st = con.createStatement();
Statement stmt = con.createStatement();
out.println("connection successfull");
int total = 0;
ResultSet rs3 = stmt.executeQuery( "SELECT COUNT(*) as total FROM reservation WHERE idRoom = '" + idRoom +
"' AND ('" + arrivaldate + "' >= arrivaldate AND '" + arrivaldate + "' <= departuredate) OR ('" + departuredate + "' >= arrivaldate "
+ "AND '" + departuredate + "' <= departuredate)");
rs3.next(); // You'll ever have only one row
total = rs3.getInt("total");
/* String query = "SELECT COUNT(*) FROM reservation WHERE idRoom = '" + idRoom +
"' AND ('" + arrivaldate + "' >= arrivaldate AND '" + arrivaldate + "' <= departuredate) OR ('" + departuredate + "' >= arrivaldate "
+ "AND '" + departuredate + "' <= departuredate)" ;
*/
// ResultSet rs2 = stmt.executeQuery(check);
out.println("<h1> Stringa check eseguito </h1>");
if( total > 0) { // THIS DOESN't WORK OF COURSE
response.sendRedirect("home.jsp");
}
else {
st.executeUpdate("insert into reservation (login,email,typeroom,idRoom,arrivaldate,departuredate)values ('"+login+"','"+email+"','"+typeroom+"','"+idRoom+"','"+arrivaldate+"','"+departuredate+"')");
}
But it doesn't work properly because it lets me to book the same room in the same data.
How can I do in your opinion? Thank you for your attention.
First, you totally ignore your total:
while(rs3.next()){
rs3.getInt("total");
}
Should be:
rs3.next(); // You'll ever have only one row
total = rs3.getInt("total");
And second, never ever use concatenations in your queries:
ResultSet rs3 = stmt.executeQuery( "SELECT COUNT(*) as total FROM reservation WHERE idRoom = '" + idRoom +
"' AND ('" + arrivaldate + "' >= arrivaldate AND '" + arrivaldate + "' <= departuredate) OR ('" + departuredate + "' >= arrivaldate "
+ "AND '" + departuredate + "' <= departuredate)");
Always use PreparedStatements instead:
PreparedStatement ps = stmt.prepareStatement( "SELECT COUNT(*) as total FROM reservation WHERE idRoom = ? AND (? >= arrivaldate AND ? <= departuredate) OR (? >= arrivaldate AND ? <= departuredate)");
int c = 0;
ps.setInt(++c, idRoom);
ps.setDate(++c, arrivaldate);
ps.setDate(++c, departuredate);
ps.setDate(++c, arrivaldate);
ps.setDate(++c, departuredate);
ResultSet rs = ps.executeQuery();
// And your usual code here
I am working with mysql and Netbeans java for my school project. Whenever I try to register the details to the sql, I get this error My SqlSyntaxErrorException:Unknown Column " [the data in the text field] in 'field list'"
Here's my code:
int age = Integer.parseInt(AgeTF.getText());
String name=NameTF.getText();
String id=IDTF.getText();
String dob=DobTF.getText();
String address=AddressTF.getText();
try {
Class.forName("java.sql.Driver");
String database = "jdbc:mysql://localhost:3306/final";
Connection conn = DriverManager.getConnection(database, "root", "sanchit");
Statement stmt = conn.createStatement();
String sql = "insert into aadhar values ( '" + id + "', " + name + ", '" + dob + "' , '" + age + "' , '" + address + "' );" ;
stmt.executeUpdate(sql);
}
catch( Exception e){
JOptionPane.showMessageDialog(null,"" + e);
}
JOptionPane.showMessageDialog(this,"You have been registered!");
Please help.
Thanks
You didn't protect name with simple quotes :
Write '" + name + "' instead of " + name + "
String sql = "insert into aadhar values ( '" + id + "', '" + name + "', '" + dob + "' , '" + age + "' , '" + address + "' );" ;
Well i have the following table Table1 in MySQL workbench--
user_id int not null,autoincrement
movie _id int not null
movie_name varchar
user_name varchar
rating int
genre varchar
Now following is the insertion into database--
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:XXXX/Recommendation1", "root",
"XXXXXXXXXXX");
Statement st = con.createStatement();
int i = st
.executeUpdate("insert into Table1(movie_Id,movie_name,user_name,rating,genre) values('"
+ movieId
+ "','"
+ mname
+ "','"
+ pname
+ "','" + ratingr + "','" + genre + "')");
out.println("Data is successfully inserted!");
} catch (Exception e) {
System.out.print(e);
Now what i want that,if there already exist a user_name with that value (pnmae),which i am entering it should not enter into my Table 1 or update,but it should enter into another table Table 2,The schema of table 2 is as following--
movie _id int not null
movie_name varchar
user_name varchar
genre varchar
For that what to use .How to use if -else condition
The following is what i am doing while checking for the username if it exists
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:XXXX/Recommendation1", "root",
"wXXXXX");
Statement st = con.createStatement();
//Statement st2 = con.createStatement();
String SQL = "SELECT * from Table1 WHERE user_name ='" + pname
+ "' ";
ResultSet rs = st.executeQuery(SQL);
--if (rs.) { //What to put here
int j = st
.executeUpdate("insert into Table2(movie_Id,movie_name,user_name,genre) values('"
+ movieId
+ "','"
+ mname
+ "','"
+ pname
+ "','" + genre + "') ");
}
int i = st
.executeUpdate("insert into Table1(movie_Id,movie_name,user_name,rating,genre) values('"
+ movieId
+ "','"
+ mname
+ "','"
+ pname
+ "','" + ratingr + "','" + genre + "') ");
/* ResultSet rs = st1.executeQuery();
out.println("name is already there");
out.println("Data is successfully inserted!"); */
/* final String Query = "SELECT t1.user_Id from Table1 t1 JOIN Table2 t2 on t2.movie_Id = t1.movie_id WHERE t2.user_name = 'vishal'";
PreparedStatement st11 = con.prepareStatement(Query);
ResultSet rw = st11.executeQuery();
rw.last();
int id = rw.getInt("user_Id");
System.out.print("ID: " + id);*/
Thanks
Try this :-
boolean isUser=false;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:XXXX/Recommendation1", "root",
"wXXXXX");
Statement st = con.createStatement();
String SQL = "SELECT 1 from Table1 WHERE user_name ='"+ pname
+ "' ";
ResultSet rs = st.executeQuery(SQL);
isUser=rs.next();
Statement st2 = con.createStatement();
if (isUser) { //check the user is exist or not
int j = st2.executeUpdate("insert into Table2(movie_Id,movie_name,user_name,genre) values('"
+ movieId
+ "','"
+ mname
+ "','"
+ pname
+ "','" + genre + "') ");
}else{
int i = st2.executeUpdate("insert into Table1(movie_Id,movie_name,user_name,rating,genre) values('"
+ movieId
+ "','"
+ mname
+ "','"
+ pname
+ "','" + ratingr + "','" + genre + "') ");
}
Hope this will help you.
i am trying to do the following and it doesnt accept it.
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID ="' + cu_ID + "'";
select from two tables and two values( variables)
Try this:
String sql_eco = "select * +
from orders +
where EmployeeID=" +e_ID + " and CustomerID ='" + cu_ID + "'";
^
Try, assuming CustomerID and EmployeeID are both Integer column type
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID =" + cu_ID;
Use this. you have misplaced " for CustomerId
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID ='" + cu_ID + "'";
values variable u wanna say something like this?
String sql_eco = "select * +
from orders +
where 1=1 ";
if(e_ID != null) {
sql_eco += " AND EmployeeID=" +e_ID ;
}
if(cu_ID != null){
sql_eco += " and CustomerID ='" + cu_ID + "'";
}
to improve this code u can use stringbuilder/stringbuffer
It says I ended this statement wrong when if I input it into sql plus with just the addition of ; it works perfectly. What am I doing wrong?
Statement statement = connection.createStatement();
statement.executeUpdate("delete from aplbuk MODEL = '"+ textField_4.getText() + "'AND year = '" + textField_1.getText() + "' AND Litres = '" + textField_2.getText()
+ "' AND ENGINE_TYPE = '" + textField_3.getText() + "'");
statement.close();
Keyword where is missing after table name aplbuk in your query delete from aplbuk MODEL.
Update the query as:
statement.executeUpdate("delete from aplbuk where MODEL = '"+
textField_4.getText() + "'AND year = '" +
textField_1.getText() + "' AND Litres = '" +
textField_2.getText() + "' AND ENGINE_TYPE = '" +
textField_3.getText() + "'");
Also if year and Litres are numeric fields then don't enclose the value in single quotes.