Database query and Java - java

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

Related

Control data in the database with Java

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)

Having Syntax Error in code java

Why is there a syntax error in this code?
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num + ","
+ "Email = '" + email_add + "',"
+ "Address = '" + mail_add + "',"
+ "SurveyStatus = " + radio_group + ","
+ "Subscription = " + receive_info +
"WHERE membership_ID = '" + member_ID';
I thought my code was right.
If it is the error in your code, check all the variables that you have used are declared and initialized with proper values.
If it is the syntax of the sql that is bothering you , here is what your sql would look like if all the variables are initialized to null.
UPDATE Customers SET (Contact)null,Emailnull,Address,null,SurveyStatus,null,SubscriptionnullWHERE MembershipID =null
Use spaces in your strSqlUpdate to correct the above sql.
EDIT
What you need is something like this.
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num
+ ",Email = '" + email_add + "'"
+ ",Address = '" + mail_add + "'"
+ ",SurveyStatus = '" + radio_group + "'"
+ ",Subscription = '" + receive_info + "' "
+ "WHERE membership_ID = '" + member_ID + "'";
I get no syntax errors when I declare and Initialize all of the variables. You have to make sure they're all initialized, within the scope of the strSqlUpdate
String contact_num = "";
String email_add = "";
String mail_add = "";
String radio_group = "";
String receive_info = "";
String member_ID = "";
String strSqlUpdate = " UPDATE Customers SET (Contact)" + contact_num + "," + "Email"
+ email_add + "," + "Address" + "," + mail_add + "," + "SurveyStatus" + "," + radio_group
+ "," + "Subscription" + receive_info + "WHERE MembershipID =" + member_ID;
Also considering you're talking about SQL syntax, adding on to what others have said, I'd advise you should use a PreparedStatement to avoid SQL injection.
PreparedStatement pst = conn.prepareStatement(
"UPDATE Customers SET (Contact) ?, ?, ?, ?, ?, ?, ? WHERE ? = ?");
pst.setString(1, contact_num);
pst.setString(2, email_add);
... and so on
An error in your current SQL syntax is this
"Subscription" + receive_info + "WHERE MembershipID
Translated as
"...Subscrptionreceive_infoWHERE MembershipID..."
You need to add spaces wherever you don't have commas

Checking for usename in mysql ...If it exist then inserting into other table Otherwise the base table

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.

Sql statement Java between 2 tables and 2 values ( variables)

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

JDBC delete statement with multiple columns

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.

Categories