update current date and time to db using sql from Java code - java

i have a table "queue_in_progress" whose structure is like the following :
I want to update the DATE_TIME_TOKEN_TAKEN , CE_PK , Service_status of the table . For this , I have the following code :
String sqlQuery = "UPDATE queue_in_progress\n" +
"SET CE_PK="+ce_pk+" ,SERVICE_STATUS=1 \n" +
"WHERE CATEGORY_PK="+Category_PK+" AND TOKEN_NO="+ Token_PK+" "
+ " AND SERVICE_COUNTER="+service_counter+" AND SERVICE_CENTER_PK="+service_center+" ;";
java.util.Date utilDate = new Date(); // Convert it to java.sql.Date
java.sql.Date date = new java.sql.Date(utilDate.getTime());
PreparedStatement stmt = con.prepareStatement(sqlQuery);
stmt.setDate(1, date);
success = stmt.executeUpdate();
But the success flag is returning -1 and the table is not updated . What is the problem ? What can I do to fix this problem ?

I don't see DATE_TIME_TOKEN_TAKEN=? in your query (the bind parameter), I think you wanted
String sqlQuery = "UPDATE queue_in_progress SET DATE_TIME_TOKEN_TAKEN=?, "
+ "CE_PK=" + ce_pk
+ ", SERVICE_STATUS=1 WHERE CATEGORY_PK="
+ Category_PK
+ " AND TOKEN_NO="
+ Token_PK
+ " AND SERVICE_COUNTER="
+ service_counter + " AND SERVICE_CENTER_PK=" + service_center;

OR if you want DATE_TIME_TOKEN_TAKEN to ALWAYS hold Current Time value, you can Set it on your Database side, no need to set it in your code.
ALTER TABLE queue_in_progress
MODIFY DATE_TIME_TOKEN_TAKEN DEFAULT CURRENT_TIMESTAMP;

Related

I can not use java.sql.date in java program correctly, it seems like there are some problems at the result set

String content = "SELECT * FROM " + "floor" + floor + " WHERE Roomnumber ='" + roomresult + "'";
System.out.println("next query->" + content);
statement.execute(content);
ResultSet rs = statement.getResultSet();
Date u = rs.getDate("CheckIn");
I want to transform the java.sql.date into java.util.date. I think the
final sentence is correct , but the java told me that there is a
NullPointerExceptio
if u want convert java.sql.date to java.util.date, use :
new java.util.Date(rs.getDate("CheckIn").getTime())
NullPointerException , may be CheckIn cloum not exist, or it be null;
pleas make sure CehckIn field exist and is not be null;

how to load data from mysql using in between two dates

In the code below using java, I am trying to get data from mysql between two choosed dates and load it into table jTable1 but the problem is when I run the data loads correctly but not until the second date.
For example, if first date is 2020-1-1 and second date is 2020-1-31 the data loads from the day of 1 to the day of 30 not until the day of 31. The last day is missing! And if I choose dates from 2020-01-01 to 2020-02-01 it loads from 2020-01-01 to 2020-01-31.
java.sql.Timestamp timestamp = new java.sql.Timestamp(jDateChooser5.getDate().getTime());
java.sql.Timestamp timestamp2 = new java.sql.Timestamp(jDateChooser6.getDate().getTime());
String sql2 = "SELECT sum(`msareffishmarket`.`Amount` ) FROM `manfz`.`msareffishmarket` \n"
+ "Where `msareffishmarket`.`place` = 'محل الأسماك' And ( `msareffishmarket`.`MsarefDate` between '" + timestamp + "' And '" + timestamp2 + "' ) "
+ " group by DATE(`msareffishmarket`.`MsarefDate`)";
stm2 = conn.prepareStatement(sql2);
rs2 = stm2.executeQuery(sql2);
// JOptionPane.showMessageDialog(this, rs.getDouble(4));
jTable3.setModel(DbUtils.resultSetToTableModel(rs2));
You are using your prepared statement incorrectly (though you are correct to think to use one). Consider this version of your code:
String sql = "SELECT MsarefDate, SUM(Amount) AS total FROM manfz.msareffishmarket ";
sql += "WHERE place = 'محل الأسماك' AND MsarefDate BETWEEN ? AND ? GROUP BY MsarefDate";
stm2 = conn.prepareStatement(sql);
stm2.setTimestamp(1, timestamp);
stm2.setTimestamp(2, timestamp2);
rs2 = stm2.executeQuery(); // do not pass the query string here
Edit:
Per the correct observations of #mangusta (see below), you should be using a date/timestamp range to search for your records. Assuming you wanted all records from January 2020, you should be using:
WHERE MsarefDate >= '2020-01-01' AND MsarefDate < '2020-02-01'

Pass a date as an argument

I did a SQL query in Java as follows:
"SELECT A.ID_MACHINE, A.HEURODATAGE, A.COMPTEUR, B.LIBELLE_IDMACHINE, C.LIBELLE_STATUT, C.CODE_COULEUR FROM ROXJAVA.MACH0004 A " +
"JOIN ROXJAVA.MACH0003 B ON A.ID_MACHINE = B.ID_MACHINE " +
"JOIN ROXJAVA.MACH0002 C ON B.CODE_MACHINE = C.CODE_MACHINE " +
"WHERE A.ID_MACHINE = ? AND A.HEURODATAGE BETWEEN '?' AND '?' AND A.CODE_STATUT = C.CODE_STATUT AND C.CODE_COULEUR = ? " +
"ORDER BY A.HEURODATAGE DESC";
In my WHERE it finds "Heurodatage" which must contain a time and a date with this format:
'2018-07-03 09:30:00.000'
I then want to retrieve the results of this query with the help of a method that takes into account the different attributes that I need to replace the? in my request.
But now I can not determine the type of my dates.
I'm getting "type not match" when I try to run with a String.
If the column is a date column, you want to pass in a date type:
PreparedStatement ps = ...;
ps.setDate(N, java.sql.Date.valueOf(your_date_value));
where it would be best if your_date_value is a java.time.LocalDate, but could also be parsed from a String (in a valid format).

How to retrieve a data between dates

I have 2 tables. A booking table and a room table. In the booking table I have the following columns: BookingID StartDate EndDate CustomerID RoomID
In the Room table I have the following columns: RoomID RoomSize
I am creating a booking system. I want to be able to query the database where I am able to get a list of rooms that are booked between 2 dates which are also based on size (small, medium or large) types.
E.g. if user clicks on small room and enters dates between 2010-02-02 to 2010-02-25 then 4 should appear as my database contains 4 small rooms that are booked between those dates.
This is what I have so far:
String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize is " + type + ") AND ((Booking.StartDate between "+ startD +" AND " + endD + ") OR (Booking.EndDate between "+ startD + " AND " + endD + "))";
This is the error I am getting:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Medium) AND ((Booking.StartDate between 2016-02-09 AND 2016-02-09) OR (Booking.E' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
I am new to SQL and having trouble doing this. Also, is my logic right?
startD and endD represents the dates that the user has entered and typeOfRoom represent the type of the room the user wants to book; e.g. eithier Small, Medium or Large
Do not use string concatenation to insert user-supplied values into SQL, especially for strings. It will leave you open to SQL Injection attacks, and SQL syntax issues. Use a PreparedStatement.
Also, replace is with =.
String sql = "select RoomID" +
" from Booking" +
" where RoomID in (" +
"select Room.RoomID" +
" from Room" +
" where Room.RoomSize = ?" +
")" +
" and ((Booking.StartDate between ? AND ?)" +
" or (Booking.EndDate between ? AND ?))";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, type);
stmt.setDate (2, startD);
stmt.setDate (3, endD);
stmt.setDate (4, startD);
stmt.setDate (5, endD);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
// code here
}
}
}
The date handling look ok I think, but you need to quote the type string in the statement. And you should not use is, just use normal =
String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize = '" + type + "') AND ((Booking.StartDate between "+ startD +" AND " + endD + ") OR (Booking.EndDate between "+ startD + " AND " + endD + "))";
Can you try if this statement works? I have replaced the 'is' keyword with '=' operator and put all the variables between "".
String sqlStatement = "select RoomID from Booking where RoomID in (select Room.RoomID from Room where Room.RoomSize = \"" + type + "\") AND ((Booking.StartDate between \""+ startD +"\" AND \"" + endD + "\") OR (Booking.EndDate between \""+ startD + "\" AND \"" + endD + "\"))";

Passing date type variable as method parameter in java

This is in the Main class
Contest c = new Contest();
c.setAnnouncementDate("2014-03-02");
Contest.addContest(c);
I am trying to insert this date in my mysql table. But it gives type incompatibility.
So we tried this code:
Contest c = new Contest();
SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
java.sql.Date da = new java.sql.Date(f.parse("2014-04-02").getTime());
c.setAnnouncementDate(da);
Contest.addContest(c);
there is a addContest(Contest cont) method in Contest class which is used to insert the dates in mysql table:
code used is:
PreparedStatement s = con.prepareStatement("Insert into " + TABLENAME + " ( " + CONTESTID + " , " + ANNOUNCEMENTDATE + " , " + RESULTDECLARATIONDATE + " , " + SUBMISSIONSTARTDATE + " , " + SUBMISSIONENDDATE + " , " + REWARD + " ) VALUES ( ?,?,?,?,?,?)");
we inserted date using :
s.setDate(2, (java.sql.Date) cont.getAnnouncementDate());
here, it always inserts 2014-01-02 date in mysql table, irrespective of our argument that we pass.
please help me.

Categories

Resources