I've run into a stubborn problem when entering date into MySQL using Java. In my code I am converting a java.util.Date to a java.sql.Date in order to quick and easy match the SQL formatting for dates.
Below is the code I am using to insert date into the database. Note: The code is shortened to only express my problem.
The client object is passed through the arguments of the function.
//Date to Date
java.sql.Date sqlBirthday = new java.sql.Date(client.getBirthday().getTime());
System.out.println(sqlBirthday); // Prints YYYY-MM-DD
sql = "INSERT INTO clientdata (client_id, weight, height, birthday) VALUES (" + client.getID() + "," + client.getWeight() + "," + client.getHeight().getMeasurementInInches() + ","
+ sqlBirthday + ")";
statement.execute(sql);
statement.close();
After executing the code to enter the data into the database, I recieve the following run-time error:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '1990' for column 'birthday' at row 1
The println outputs the following:
1998-05-03
Which is expected output.
The stack trace for the error is below, but I doubt it has much use:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '1990' for column 'birthday' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3833)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3771)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2531)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2489)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:848)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:742)
at fitness.traingym.client.utils.DatabaseHandler.createLogin(DatabaseHandler.java:71)
at fitness.traingym.client.TrainManagement.testClientCreate(TrainManagement.java:47)
at fitness.traingym.client.TrainManagement.<init>(TrainManagement.java:22)
at fitness.traingym.client.TrainManagement.main(TrainManagement.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
This is interesting I'm running into this error as the formatting for the date seems to be correct for SQL syntax.
Easiest way to solve the problem is surrounding the date string with quote ', but this is a nasty trick and MUST BE AVOIDED AT ALL. The best way to solve this and work with parametrized queries is to use PreparedStatements:
sql = "INSERT INTO clientdata (client_id, weight, height, birthday) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInteger(1, client.getID());
pstmt.setInteger(2, client.getWeight());
pstmt.setInteger(3, client.getHeight());
pstmt.setTimestamp(4, new java.sql.Timestamp(client.getBirthday().getTime()));
pstmt.executeUpdate();
pstmt.close();
The problem is that the date value needs to be embedded in single quotes (') before being passed in to the database.
Update your Java string to include single quote marks (') around the value of sqlBirthday.
String date = request.getParameter("date");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // your template here
java.util.Date dateStr = formatter.parse(sqlBirthday );
java.sql.Date dateDB = new java.sql.Date(dateStr.getTime());
Pass it in this java.sql.Date in prepared statement.
Use single quote enclosed in date value
Use
sql = "INSERT INTO clientdata (client_id, weight, height, birthday) VALUES (" + client.getID() + "," + client.getWeight() + "," + client.getHeight().getMeasurementInInches() + ", '"+ sqlBirthday + "')";
^ ^
Changing SimpleDateFormate to ("yyyy-MM-dd") while setting your DateChooser property format as ("dd-MM-yyyy") worked for me.
Here's an example:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dob = sdf.format(BirthDayR.getDate());
prepareStatement.setString(9, dob);
I hope this helped.
Related
So I'm trying to get a basic sql string to work where it will grab the records in the sqlite database based on between dates. However, for some reason, it doesn't work. I just don't understand why.
private void viewTransactionsBetweenDatesTable(){
//Sets the table to view transactions between certain dates
try{
//Get's the dates from startDateChooserTransactions1 and endDateChooserTransactions1
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("MMM dd, yyyy");
Date sdct = startDateChooserTransactions1.getDate();
Date edct = endDateChooserTransactions1.getDate();
String sdcts = df.format(sdct);
String edcts = df.format(edct);
String sdctlabel = df2.format(sdct);
String edctlabel = df2.format(edct);
//Child's ID
String cid = childIDCheck1.getText();
//Grab's the specified data and places that as the table
String sql = "SELECT * FROM ChildrenPayment WHERE ChildID='"+cid+"' AND strftime('%Y-%m-%d', 'Report Transaction Date') BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
//Sets up the table
Info1.setModel(DbUtils.resultSetToTableModel(rs));
TableColumnModel tcm = Info1.getColumnModel();
//tcm.removeColumn(tcm.getColumn(3));
// tcm.removeColumn(tcm.getColumn(3));
// tcm.removeColumn(tcm.getColumn(10));
// tcm.moveColumn(11, 10);
// tcm.removeColum(tcm.getColumn(13));
//Changes modLabel1
modLabel1.setText(firstNameEditClass1.getText() + " " + lastNameEditClass1.getText() + " Between " + sdctlabel + " - " + edctlabel);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally{
try{
pst.close();
rs.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I am using a jdatechooser so I am sort of forced to use SimpleDateFormat compared to the better DateTimeFormatter. Anyway, I'm formatting it according to YYYY-MM-DD like sqlite likes, but when I run the function, the table does not display anything. I set the days pretty wide (Feb 01, 2018 to Feb 14, 2018) and the date in my database is Feb 07, 2018. I have a few records in the database for it to pull. However, it just doesn't do it. And no error is popping up, so I do not know why it is not working.
Image of the records that I'm trying to place into my jtable
Edit1: Before I forget, I also tried the following SQL string
String sql = "SELECT * FROM ChildrenPayment WHERE ChildID='"+cid+"' AND 'Report Transaction Date' BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
This will not work:
strftime('%Y-%m-%d', 'Report Transaction Date')
because the format specifiers you have provided require that you supply three values, one each for year, month, and day.
If the dates in the database are stored as complete SQLite datetime strings, you will have to use
"... date([Report Transaction Date]) BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
Note square brackets (not single quotes) around column name. This has nothing to do with needing a date/time value, it's because the column name has spaces in it. Any column name with spaces has to be enclosed in double quotes or square brackets. That's why it's a good idea to never use spaces in column names.
If they are, in fact, stored as 'YYYY-MM-DD' strings, then the reason your alternative didn't work is because you single-quoted the column name 'Report Transaction Date', which results in comparing that literal string to the date values.
Hello so i have a these code that have you enter a year, a month, a day all string into a text field and then it will combine them to make one string and used a statement to make query convert this to date and inserting it and some other data into a database here is the code.
int CustomerID = Integer.parseInt(txtCustomerID.getText());
int CarID = Integer.parseInt(txtCarID.getText());
String startdateyear = txtStartDateYear.getText();
String startdatemonth = txtStartDateMonth.getText();
String startdateday = txtStartDateDay.getText();
String enddateyear = txtEndDateYear.getText();
String enddatemonth = txtEndDateMonth.getText();
String enddateday = txtEndDateDay.getText();
String StartDate = startdateyear + startdatemonth + startdateday;
String EndDate = enddateyear + enddatemonth + enddateday;
int HiringPrice = Integer.parseInt(txtHiringPrice.getText());
String Pay = txtPay.getText();
carDA.insert(CustomerID, CarID, StartDate, EndDate, HiringPrice, Pay);/
This is the Insert Query:
stm.executeUpdate("INSERT INTO CarOrder VALUES (" + CarID +"," + CustomerID +",CONVERT(DATE," + "'" +StartDate+ "', 111), CONVERT(DATE," + "'" +EndDate+"', 111)," +HiringPrice+ "," +"'"+Pay+ "')");
When i run the program it throws this message:
Conversion failed when converting date and/or time from character string.
I cant seem to find out why it is doing this, if any one can help me i will be thankful.
It seems that the date format you enter is not correct is should look like :
convert(datetime, '2017/06/24', 111) -- yyyy/mm/dd
because you are using the 111 so your input should look like yyyy/mm/dd, read more about this CAST and CONVERT (Transact-SQL)
To avoid syntax error or SQL Inject i suggect to use PreparedStatement instead, it is more helpful and more secure.
DateFormat format = new SimpleDateFormat("yyyy/mm/dd");
String query = "INSERT INTO CarOrder VALUES (?, ?, CONVERT(DATE, ?, 111), CONVERT(DATE, ?, 111), ?, ?)";
try (PreparedStatement insert = connection.prepareStatement(query)) {
insert.setInt(1, CustomerID);
insert.setDate(2, new Date);
insert.setDate(3, format.parse(StartDate));
insert.setDate(4, format.parse(EndDate));
insert.setDouble(5, HiringPrice);//i think the price is a double maybe you make it int or float so you have to use the right type
insert.setString(6, Pay);
insert.executeUpdate();
}
You are getting invalid string here:
String StartDate = startdateyear + startdatemonth + startdateday;
For example, startdateyear = '2016', startdatemonth = '4', startdateday = '1' --> StartDate = '201641' --> select CONVERT(DATE,'201641', 111) -->
Msg 241, Level 16, State 1, Line 1 Conversion failed when converting
date and/or time from character string.
Why on the earth do you use 111 format that is yy/mm/dd while your string does not contain / at all? That '201641' is interpreted like year=2020, month=16, day=41
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 am trying to insert date and time to a table in MySQL db from a JSP page but ended with an error:
Severe: java.sql.SQLException: Incorrect datetime value: '15/05/2015 14:00:00' for function str_to_date
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
Date format in JSP page is dd/MM/yyyy HH:MM
For ex, the date is 15/05/2015 and time is 14:00
How can I fix the problem or what is correct way of doing it?
the stored procedure:
CREATE... PROCEDURE `Add(Id int,
Date_In varchar(50),Out result int)
BEGIN
IF (select count(*) from myTable Where DATE_FORMAT(Datein, '%d/%m/%Y')=DATE_FORMAT(Date_In, '%d/%m/%Y') and id=Id) < 1 then
BEGIN
INSERT INTO myTable (id, DateIn)
VALUES (id,str_to_date(Date_In,'%d/%M/%Y %H:%i'));
set result=1;
END;
END if;
end
java code:
String date = request.getParameter("date");
String time = request.getParameter("time");
String dateTIme = date + " " + time + ":00";
and insert statement goes here.
could you change
VALUES (id,str_to_date(Date_In,'%d/%M/%Y %H:%i')
to
VALUES (id,str_to_date(Date_In,'%d/%m/%Y %H:%i:%s'));
?
You are missing seconds as per the exception
You have used str_to_date(Date_In,'%d/%M/%Y %H:%i').
According to this link, %M signifies that the month is being specified in the name format. In your case, you should change your format to %d%m%Y, or alter your input to 15/MAY/2015.
Here I am going to get data based on date only but my data continence both date and time here I am using like query to select that data based on date but I am not getting it can any plz exp line it thanks.
String device = "NR09G05635";
String date = "2013-11-29";
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(date);
java.sql.Date date1 = new java.sql.Date(temp.getTime());
sql = "select * from gpsdata1 where deviceId=? and dateTime like '" + date1 + "'";
System.out.println("sql" + sql);
ps1 = con.prepareStatement(sql);
ps1.setMaxRows(1);
ps1.setString(1, device);
ps1.execute();
rs = ps1.getResultSet();
-You use the LIKE operator to compare a character, string, or CLOB value to a pattern. Case is significant. LIKE returns the BOOLEAN value TRUE if the patterns match or FALSE if they do not match
Use TO_CHAR to explicitly create a string based on a DATE, using the format you want. Don't rely on implicit conversions.
Select *
From gpsdata1
Where NVL ( TO_CHAR ( dateTime
, 'YYYY-MM-DD HH:MI:SS AM'
)
, ' ' -- One space
) Like '%';
SELECT * FROM gpsdata1
WHERE deviceId=? and CONVERT(VARCHAR(25), dateTime, 126) LIKE '2013-11-19%'
LIKE operator does not work against DATETIME variables, but you can cast the DATETIME to a VARCHAR