The query works fine but since I must test my project several time and I dont want always to adjust the arrivaltime table to the current time I would integrate a string time to the query but I am getting the following error
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 ':56,'%H:%i') and name LIKE 'hbf'' at line 1
The time must include only the hours as well minutes digits.
String time = "12:56:00";
PreparedStatement preparedTime = con
.prepareStatement("SELECT route from arrivaltimes INNER JOIN stops"
+ " ON arrivaltimes.stop_id=stops.stop_id "
+ "WHERE weekday = '"
+ day
+ "'"
//+ " and time_format(arrivaltime,'%H:%i')= time_format(curtime() ,'%H:%i') and name LIKE '"
+ " and time_format(arrivaltime,'%H:%i')= time_format("+ time+ ",'%H:%i') and name LIKE '"
+ stop_name + "'");
ResultSet rsArrivaletime = preparedTime.executeQuery();
When using PreparedStatement, NEVER CONCATENATE STRINGS TO GET THE QUERY, EVER. Pass the proper time as java.sql.Time or java.sql.Timestamp as parameters.
String sql =
"SELECT route FROM arrivaltimes INNER JOIN stops"
+ " ON arrivaltimes.stop_id = stops.stop_id"
+ " WHERE weekday = ?"
+ " and arrivaltime = ?"
+ " and name LIKE ?";
PreparedStatement preparedTime = con
.prepareStatement(sql);
preparedTime.setString(1, day);
//preparing the proper time using java.util.Calendar
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 56);
cal.set(Calendar.SECOND, 0);
//create an instance of java.sql.Time
//Calendar#getTime returns an instance of java.util.Date
//Date#getTime returns the time in millis (long)
Time time = new Time(cal.getTime().getTime());
//setting the time
preparedTime.setTime(2, time);
preparedTime.setString(3, stopname);
ResultSet rs = preparedTime.executeQuery();
Related
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;
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'
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).
When attempting to get details from an MS Access database using the following code:
//returns the details of a specific employee for use in the update GUI
public static String getEmployeeDetails(int empID) throws SQLException{
String employee = "";
Statement stmt = conn.createStatement();
String query = "SELECT employeetbl.Department, "
+ "employeetbl.Surname, "
+ "employeetbl.FirstName, "
+ "employeetbl.CurrentPosition, "
+ "FORMAT(employeetbl.DateOfBirth, 'yyyy/mm/dd') AS DateOfBirth, "
+ "employeetbl.TotalYearsRelevantExperience, "
+ "employeetbl.HighestQualification, "
+ "employeetbl.EmailAddress, "
+ "employeetbl.PhoneNo, "
+ "FORMAT(employeetbl.DateOfEmployment, 'yyyy/mm/dd') AS DateOfEmployment "
+ "FROM employeetbl WHERE EmployeeID = "+empID+";";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
employee = rs.getString("Department")
+"#"+rs.getString("Surname")
+"#"+rs.getString("FirstName")
+"#"+rs.getString("CurrentPosition")
+"#"+rs.getString("DateOfBirth")
+"#"+rs.getString("TotalYearsRelevantExperience")
+"#"+rs.getString("HighestQualification")
+"#"+rs.getString("EmailAddress")
+"#"+rs.getString("PhoneNo")
+"#"+rs.getString("DateOfEmployment");
}
return employee;
}
called from this method:
if(cmbTable.getSelectedItem().equals("Employees")){
String[] tmp = cmbRecord.getSelectedItem().toString().split("-");
int empID = Integer.parseInt(tmp[0]);
String employeeDetails = Master.getEmployeeDetails(empID);
String[] employee = employeeDetails.split("#");
cmbDepartment.setSelectedItem(employee[0]);
txtSurname.setText(employee[1]);
txtFirstName.setText(employee[2]);
txtCurrentPos.setText(employee[3]);
txtDOB.setText(employee[4]);
txtExperience.setText(employee[5]);
txtQualification.setText(employee[6]);
txtEmail.setText(employee[7]);
txtPhone.setText(employee[8]);
txtEmployment.setText(employee[9]);
}
I am met with the following error
error: net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.0 Java execution: FORMAT
I have no idea what is causing this error since the SQL works perfectly fine when executed in Access and the format is needed otherwise it outputs the records information including the time which is not set or used.
I'd remove the FORMAT from your SQL string and format the date in Java. I do not know what the format of the date is being returned as, but this should allow you to parse it and then input the fields in the Calendar.set() method as shown here:
public static void main(String[] args) {
final Calendar calendar = Calendar.getInstance();
calendar.set(2015, Calendar.AUGUST, 21, 9, 27);
final Date date = calendar.getTime();
final String formattedDate = new SimpleDateFormat("yyyy/MM/dd").format(date);
System.out.println("formattedDate = " + formattedDate);
}
For future readers: the format function is implemented in ucanaccess and the code originally posted is correct. So the following code runs fine with ucanaccess:
select format(#2001-03-02#, 'yyyy/mm/dd') from dual.
Nevertheless there is a lack in the handling of null arguments, which likely causes the issue. So
select format(null, 'yyyy/mm/dd') from dual; causes an exception to be thrown.
Even if I fixed this issue, a casting of the null values to timestamp would be needed using a specific hsqldb syntax, because of the ambiguity with the function FORMAT(varchar,varchar) and FORMAT(double,varchar).
So I suggest this (simplified) workaround:
select nvl2(employeetbl.DateOfBirth,FORMAT(employeetbl.DateOfBirth, 'yyyy/mm/dd'),null) AS DateOfBirth from ...
Notice that, as well as in access, mm means month (and not minutes).
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;