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.
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.
I try to retrieve records from ORACLE database table using JDBC thin driver.
The prepared statement I'm using:
(1)
SELECT (t1.LOGGED_TIME - ?) AS TDIFF, t1.ID, t1.STATUS, t1.LOGGED_TIME, t1.SERVER_TIME
FROM table_1 t1
WHERE (
((t1.LOGGED_TIME - ?) <= INTERVAL '10' DAY)
AND ((t1.LOGGED_TIME - ?) >= INTERVAL '-10' DAY))
ORDER BY t1.LOGGED_TIME DESC
where t1.LOGGED_TIME represents a timestamp column. Every three parameters are identical timestamps set with
java.sql.Timestamp controlTime = Timestamp.valueOf("2014-08-15 03:52:00");
lookupTime.setTimestamp(1, controlTime);
lookupTime.setTimestamp(2, controlTime);
lookupTime.setTimestamp(3, controlTime);
Executing the code works fine - no exceptions or warnings are displayed. Nevertheless the resultset returned by
rs = lookupTime.executeQuery();
is empty.
Setting the query to
(2)
SELECT (t1.LOGGED_TIME - TO_TIMESTAMP('2014-08-15 03:52', 'yyyy-mm-dd hh24:mi')) AS TDIFF, t1.ID, t1.STATUS, t1.LOGGED_TIME, t1.SERVER_TIME
FROM table_1 t1
WHERE (
((t1.LOGGED_TIME - TO_TIMESTAMP('2014-08-15 03:52', 'yyyy-mm-dd hh24:mi')) <= INTERVAL '10' DAY)
AND ((t1.LOGGED_TIME - TO_TIMESTAMP('2014-08-15 03:52', 'yyyy-mm-dd hh24:mi')) >= INTERVAL '-10' DAY))
ORDER BY t1.LOGGED_TIME DESC
returns the expected data.
When I query e.g. strings from another column of the same table with a prepared statement the result is ok.
What I'm missing here? Where is the point? Any idea?
To say it clear: the point is not to identify a kind of wrong date/time format conversion in (2). That will always lead to an oracle error message and can be fixed easily.
The question is: why stays the RecordSet returned by the preparedStatement (1) empty (= not a single record) without any error notification? If the Timestamp format is wrong in any way, why there isn't an error or a warning?
Check your TO_TIMESTAMP format:
TO_TIMESTAMP('2014-08-15 03:52',
'dd.mm.yy hh24:mi')
Aug. 14, 2015, not Aug. 15, 2014
Update
Actually, I get the following error when trying that one:
ORA-01843: not a valid month
01843. 00000 - "not a valid month"
Update2
A Java Timestamp maps to an Oracle DATE data type, not a TIMESTAMP. Don't know if that makes a difference, but you might try TO_TIMESTAMP(?).
I would however change the query to allow use of a potential index on LOGGED_TIME:
SELECT ID, STATUS, LOGGED_TIME, SERVER_TIME
FROM table_1
WHERE LOGGED_TIME BETWEEN ? AND ?
ORDER BY LOGGED_TIME DESC
Then do all the math in Java:
Timestamp controlTime = Timestamp.valueOf("2014-08-15 03:52:00");
Calendar cal = Calendar.getInstance();
cal.setTime(controlTime);
cal.add(Calendar.DAY_OF_MONTH, -10);
lookupTime.setTimestamp(1, new Timestamp(cal.getTimeInMillis()));
cal.setTime(controlTime);
cal.add(Calendar.DAY_OF_MONTH, 10);
lookupTime.setTimestamp(2, new Timestamp(cal.getTimeInMillis()));
try (ResultSet rs = lookupTime.executeQuery()) {
while (rs.next()) {
long tdiffInSeconds = (rs.getTimestamp("LOGGED_TIME").getTime() - controlTime.getTime()) / 1000;
// other code
}
}
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.
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
String x=jTextField1.getText();
After connecting to the database the query is:
String query="INSERT INTO student(A) VALUES('"+a+"') where date=' " +x+ " ';";
stmt.executeUpdate(query);
*a is a string which has a letter P assigned to it.
The error i am getting is "....check your mysql syntax....corresponding to the date='"+x'"; "
I want to compare the date entered in the textfield to the date in the mysql 'date' column and if it is correct,the 'a' value (which is P) should be written in column A in the same row of the date entered...
Please help...
Thank you...
I see a space after/before the single quote.
Furthermore date is also an SQL keyword, so better not use that as field name. You could write
`date`
Addition
Sorry, I realized that I erred (date cannot be a field queried as we are inserting a new record).
Either you mean:
String query = "INSERT INTO student(A) VALUES('P') WHERE CURRENT_DATE() = '2012-05-09'";
Or date is a field, and you just want to set another field:
String query = "UPDATE student SET A = 'P' WHERE `date` = '2012-05-09'";
Inserting new records into same table
This is not allowed to do immediately, so one has to use a temporary table.
CREATE TEMPORARY TABLE tmp (A VARCHAR(1));
INSERT INTO tmp (A)
SELECT 'P' FROM student WHERE dt = '...';
INSERT INTO student(A)
SELECT A FROM tmp;
DROP TABLE tmp;