Saving a Date to MySQL database [duplicate] - java

Can anyone help me with a sample JSP code to store date in a MySql database through JDBC?
When I try to execute the code given below, I get the following exception:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column 'date' at row 1
How to overcome this problem? Following is my code:
Connection con = null;
String StaffName = request.getParameter("StaffName");
// String subcode = request.getParameter("subcode");
String hourId = request.getParameter("hourId");
if (hourId == null)
hourId = "";
String day = request.getParameter("day");
if (day == null)
day = "";
String date = request.getParameter("date");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation", "root", "success");
// PreparedStatement stat = con.PrepareStatement();
String updateString = "INSERT INTO tblstaffallocation (StaffName,hourId,daysId,date) VALUES (?,?,?,?)";
PreparedStatement preparedStatement = con.prepareStatement(updateString);
preparedStatement.setString(1, StaffName);
preparedStatement.setInt(2, 0);
preparedStatement.setInt(3, 0);
preparedStatement.setString(4, date);
} catch (Exception e) {
out.print(e);
}

To set date to prepared statement you need change type of value:
String date = request.getParameter("date");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // your template here
java.util.Date dateStr = formatter.parse(date);
java.sql.Date dateDB = new java.sql.Date(dateStr.getTime());
now convert String date to java.sql.Date and use another method:
preparedStatement.setDate(4,dateDB);

I had a similar error. It turns out I just needed to update the jar version for mysql-connector-java (using maven)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>...</version>
</dependency>

Try reformating the date
String date = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date(request.getParameter("date")));
and then insert into the database.
Note that request.getParameter("date") should be in format 11/20/2013 for this to work or you can use a similar way to achieve.

Make sure that the Date value that you are trying to insert into the table is exactly in the format defined in the date column of your table.

I know this is an old thread, but none of these solutions solved the problem for me. What worked for me was to upgrade hibernate to version 5.2.10.Final (see this SO post).
Running Spring Boot and Spring Data JPA 1.5.4.RELEASE and hibernate 5.2.10.Final.

If someone will have similar error for entity field with Data type annotated as #Temporal, the solution for me was to replace annotation value TemporalType.TIMESTAMP by TemporalType.TIME:
#Temporal(TemporalType.TIMESTAMP)
private Date dateField;
should be like this:
#Temporal(TemporalType.TIME)
private Date dateField;
Another way to resolve this problem without any changes in code (at least for me) was to run application on higher Tomcat version, hope it will help.

Accepted answer only handles date, not datetime. Anyways...
My problem was it didn't accept really old datetime's. I generated date in .net environment, where default date was "1900-01-01 01:01:01". I had to change date to somthing later in time... Ooops.
My error message:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '1900-01-01 01:01:01' for column 'added' at row 1

Related

How to insert datetime in this - " 2016-01-01T19:33:15-05:00" format in MSSQL using Java?

I have an column defined as datetime(2) and I have to create a new date in this format - 2016-01-01T19:33:15-05:00
Entity: private Date transactionTime;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = null;
try {
date = formatter.parse(formatter.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
obj.transactionTime(date);
It is getting inserted in SQL as like this - "2021-08-26 14:19:09.0000000" but I need insert this in the format mentioned above.
There is only column type, datetimeoffset that can hold the timezone offset (e.g. -05:00 as mentioned in your question) value. Check the Data type mappings documentation to learn more about it.
So, if you want to store the timezone offset value, change the column type to datetimeoffset. After that, you will be able to insert the value which you have mentioned in the question.
You can use the following code to access the stored value:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT foo FROM mytable WHERE ...");
while (rs.next()) {
DateTimeOffset dateTimeOffset = rs.getObject(1, DateTimeOffset.class));
System.out.println(dateTimeOffset);
}
rs.close();
st.close();
where foo the name of the column of type, datetimeoffset.

How to resolve MySQLSyntaxErrorException in JDBC preparedStatement [duplicate]

This question already has answers here:
Variable column names using prepared statements
(7 answers)
Closed 5 years ago.
I have a query that throws a com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException and I can't figure out why. I am using xampp and when I try the same query directly, it works fine. I also have a whole bunch of other methods that use very similar queries that all work.
The problem seems to be with updating the date, I noticed in the error message that java puts ' ' around the date, which makes it a string and is probably the reason for the error. However I'm not sure how to fix this to insert the date as a date.
Here's the code:
public void update(int userId, String date, String column, String value){
try {
// convert date from String to Date
DateTime dt = DateTime.parse(date);
java.sql.Date sqlDate = new java.sql.Date(dt.getMillis());
// create prepared statement
conn = DriverManager.getConnection("jdbc:mysql://localhost/db","root", "");
String query = "UPDATE expenses_income SET ? = ? WHERE userId = ? AND date = CAST(? AS DATETIME);";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, column);
preparedStmt.setString(2, value);
preparedStmt.setInt(3, userId);
preparedStmt.setDate(4, sqlDate);
preparedStmt.executeUpdate();
conn.close();
} catch (Exception e) {
System.err.println("MySQL exception: " + e);
}
}
And the error message:
MySQL exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''comment' = '123' WHERE userId = 1 AND date = CAST('2018-01-06' AS DATETIME)' at line 1
I also tried the query without casting as datetime:
String query = "UPDATE expenses_income SET ? = ? WHERE userId = ? AND date = ?;";
But I get the same error.
I then tried to use java.util.Date instead of Joda DateTime, but it doesn't help. Any ideas?
Thanks!
.. right syntax to use near ''comment' = '123'
You are getting exception because column name parameterization, which is not correct.
UPDATE expenses_income SET ? = ?
It should be
UPDATE expenses_income SET column_name = ?
I also noticed a semicolon ; at the end of the SQL, which should be removed and you don't need to cast Date explicitly. It should be just
UPDATE expenses_income SET column_name = ? WHERE userId = ? AND date = ?
Also, you shouldn't name column name like date, it should be last_updated or something meaningful.

how to save & retrieve a null date from mysql db using jdatechooser

I am developing a simple hospital management system for my project with netbeans, so here is my problem in brief. When a patient admits and discharge from a hospital his/her date of admission and date of discharge should be recorded. so I put two jDateChoosers for admission and discharge. So when a new patient admits I have to keep the date of discharge jDateChooser blank and save.
I changed the date format of the jDateChoosers to "yyyy-MM-dd"
(I use mysql control center 0.9.4 to create my database and tables) firstly I tried saving the date by changing the discharge column(dod) data
type to 'date' then an exception jumped as follows.
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data truncated for column 'dod' at row
Then I tried changing the data type to 'varchar' and allowed null
values, ok no problem this time it saved blank in the db.
When retrieving patients' info I have coded the admission and discharge date to appear in the two jDateChoosers seperately. but an exception generates like this
java.text.ParseException: Unparseable date: ""
at java.text.DateFormat.parse(DateFormat.java:357)
at Patient.pidKeyReleased(Patient.java:455)
at Patient.access$000(Patient.java:23)
at Patient$1.keyReleased(Patient.java:118)
at java.awt.Component.processKeyEvent(Component.java:6466)
This is the code and the imports involved with the date problem :
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;`
This is coded in the save button
try {
Statement stmt = connection.hosp().createStatement();
String dt = ((JTextField)doa.getDateEditor().getUiComponent()).getText();
String dt1 = ((JTextField)dod.getDateEditor().getUiComponent()).getText();
stmt.executeUpdate("insert into patients values ('"+pid.getText()+"','"+nic.getText()+"','"+fname.getText()+"','"+lname.getText()+"','"+age.getText()+"','"+address.getText()+"','"+contact.getText()+"','"+ptype.getSelectedItem()+"','"+wardname.getText()+"','"+wardno.getText()+"','"+roomno.getText()+"','"+diagnosis.getText()+"','"+doctor.getText()+"','"+consultant.getText()+"','"+dt+"','"+dt1+"')");
} catch (Exception e) {
e.printStackTrace();
}
This is the search Code and it is coded in a text box and the action is keyrelease.
This is where the above stated exception java.text.ParseException: Unparseable date: "" comes.
try {
Statement s = connection.hosp().createStatement();
String ss = pid.getText().trim();
ResultSet rs = s.executeQuery("select * from patients where patient_id like ('%"+ss+"%')");
while(rs.next()){
nic.setText(nics);
fname.setText(fnames);
lname.setText(lnames);
.... etc
String datevalue=rs.getString(16);
String datevalue1=rs.getString(17);
DateFormat formatter ;
Date date, date1;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date)formatter.parse(datevalue);
date1 = (Date)formatter.parse(datevalue1);
doa.setDate(date);
dod.setDate(date1);
}
}catch (Exception e) {
e.printStackTrace();
}
if there is any other method to solve this problem please mention it.
You still havent provided all the information, So I am assuming. Anyhow this is what I have found.
dt and dt1 columns are numbered as 15 and 16 from your insert statement.
String datevalue = rs.getString(16); // Supposed to be 15
String datevalue1 = rs.getString(17); // Supposed to be 16
While getting data from columns use rs.getXXX("Column Name") (gives more visibility) instead of rs.getXXX("columnIndex").
Also use JDBC PreparedStatement. Currently your app does not avoid SQL Injection
Try not to use varchar for date datatype. Use Date Thats what they were designed for.

Parsing Date in Java

Good day everyone! I have a problem regarding my "date". It needs to be parsed but I don't know how to do it. Can someone help me by suggesting fixes on my code?
<%
String format = "yyyy-MM-dd";
DateFormat df = new SimpleDateFormat(format);
String faculty = request.getParameter("faculty");
String absent_date = request.getParameter("absent_date");
int intFaculty = Integer.parseInt(faculty);
System.out.println(faculty);
System.out.println(df.parse(absent_date));
java.sql.Date absentdate = new java.sql.Date(df.parse(absent_date).getDate());
Absences abs = new Absences();
abs.setFaculty_id(intFaculty);
abs.setAbsent_date(absentdate);
int result = AbsencesImpl.AddAbsences(abs);
if (result == 0)
{
%>
<jsp:forward page="ListAbsences.jsp">
<jsp:param name="msg" value="Record Successfully Added"/>
<jsp:param name="ret" value="meron"/>
</jsp:forward>
<%
}
%>
For the result and error in Console:
5
Tue May 01 00:00:00 CST 2012
java.sql.SQLException: 3 values for 2 columns
I found this but I dont know how to implement this on my codes.
SimpleDateFormat parserSDF=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Im using Eclipse Indigo, Sqlite, and Apache Tomcat
Insert Statement (Im using MVC)
public int AddAbsences(Absences abs)
{
Connection con = null;
PreparedStatement pstmt;
ConnDB conn = new ConnDB();
String sql = "INSERT INTO absences( faculty_id, absent_date) VALUES(?, ?)";
try{
con = conn.connect();
try{
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, abs.getFaculty_id());
pstmt.setDate(2, abs.getAbsent_date());
pstmt.executeUpdate();
}catch(Exception e){
System.out.println(e);
}
con.close();
}catch(Exception e){
System.out.println(e);
}
return 0;
}
I will recommend to use
df.parse(absent_date).getTime()
instead of
df.parse(absent_date).getDate()
And also, I suspect that you have table absences with 3 columns, but you try to insert only 2 values. If one of values from table is id, then I suspect this value is not autogenerated.
Hope it will help you.
Try to formulate a insert statement which will work from the database management console (which ever is your database), then try to substitute the same in the code with arguments. There by you will get the date format also. There are some sql date functions which you can use in the query itself which will convert the date from your code readable format.
eg: in MsSQL - cast ('20120312' as datetime) will convert the string date 12-03-2012 into date time.
try to search for sql date functions for your type of database.

Insert Date field into DB

I am having a textbox field in my jsp called "req_date". The user is selecting a date from a javascript calendar in the format of "DD-MON-YY" ex. "29-aug-2010".So, now I am stuck while trying to insert it in the DB.
I tried " String queryString = "INSERT INTO Charity (req_date) VALUES (?)", but it is not inserting. How do I solve tis out.
The req_date is type of date in the DB.
Can you please help
Date format depends upon Database you use.
For reference Date formats with Oracle.
so your query should look like :
String queryString = "INSERT INTO Charity (req_date) VALUES (to_date('29-aug-2010', 'dd-mon-yyyy'))"
This is just to answer your question. But I will prefer usage of PreparedStatement as also suggested in other answers.
Your code using PreparedStatement should look something like following: (NOTE: I have not tested this code )
String formatIn = "dd-MMM-yyyy";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-Aug-2010");
java.sql.Date sqlDate = new java.sql.Date(inDate.getTime());
PreparedStatement prest = con
.prepareStatement("INSERT INTO Charity (req_date) VALUES (?)");
prest.setDate(1, sqlDate);
int row = prest.executeUpdate();
Use a PreparedStatement and its setDate(..). Or use a timestamp (long).
It depends on your database, PostgreSQL does recognize this format:
SELECT CAST('29-aug-2010' AS date);
Result:
'2010-08-29'
In most cases, you'd better use the ISO-format yyyy-mm-dd.

Categories

Resources