I have been using Java to store some records from a csv file.
One of these records is a date. The problem here is I am using JDBC to store these records in a database. Now, the Date object of Java is showing an error while putting it into the database. I have been stuck on this for a while. Please let me know how to solve this. I have used type Date in mysql for storing it into the database. Here is the part creating the problem.
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
"VALUES("+"DATE_FORMAT("+d+","+"'%Y-%m-%d'"+"))";
stmt.executeUpdate(sql);
If I execute this directly in MySqlWorkBench, it is storing the date properly. But through JDBC it is a problem.
The error is as shown below :
com.mysql.jdbc.exceptions.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 'Jun 30 14:04:03 IST 2016,'%Y-%m-%d'))' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1402)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1317)
at payex.writeDB(payex.java:221)
at payextestdrive.main(payextestdrive.java:11)
You add d.toString() to the SQL command when you want to add the formatted date string. Also a space is missing between the table name and VALUES:
String sql = "INSERT INTO TESTING VALUES(DATE_FORMAT(" + d1.format(d) +",'%Y-%m-%d'))";
The error message is pretty clear
right syntax to use near 'Jun 30 14:04:03 IST 2016,'%Y-%m-%d'))'
The format you provided is MMM DD HH:mm:ss Z YYYY, but the system expects %Y-%m-%d
Try
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
" VALUES("+"DATE_FORMAT('"+d1.format(d)+"',"+"'%Y-%m-%d'"+"))";
stmt.executeUpdate(sql);
or simply
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
" VALUES('"+d1.format(d)+"')";
stmt.executeUpdate(sql);
Related
In my sql query I have date formating as :
to_char(crtd_ts,'YYYY-MM-DD HH24:MI:SS.FF') crtd
and my database column stores the value as 2018-4-24.8.1. 30. 404577000
What is the way of doing the same thing in Java?
I tried this way, but I am getting an error.
private String formatDate(String refCrtdTs) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH24:mm:ss.ff");
String dateInString = refCrtdTs;
try {
Date date = sdf.parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
I am trying to replace the above sql query with hibernate criteria. My hibernate entity for the column is defined as
#Column(name="REF_CRTD_TS",columnDefinition="timestamp")
private String refCrtdTs;
and the column type in Oracle is Timestamp.
So hibernate criteria returns me this value as String which I want to format now.
Try this,
yy-M-d H:m:s.F
And your database column stores the value should be "2018-4-24 8:1:30.114"
F is Day in year (example: Feb 1st => F = 32, 31 day in Jan + 1 day in Feb)
You have to match same patter as per your sql, just try the same pattern to get in Java
I think this will work, please comment if you required more info
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS aa");
I wish to produce a current timestamp in the format of yyyy-MM-dd HH:mm:ss. I have written up the following code, but it always gives me this format yyyy-MM-dd HH:mm:ss.x
How do you get rid of the .x part ?
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime);
I need to have a timestamp type for writing into mysql.
Probably you're looking at the String representation the Timestamp object gives in your database engine or its Java representation by printing it in the console using System.out.println or by another method. Note that which is really stored (in both Java side or in your database engine) is a number that represents the time since epoch (usually January 1st 1970) and the date you want/need to store.
You should not pay attention to the String format it is represented when you consume your Timestamp. This can be easily demostrated if you apply the same SimpleDateFormat to get a String representation of your timestamp object:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime)
//will print without showing the .x part
String currentTimeFromTimestamp = df.format(currentTime);
Anyway, if you want the current time, just create the Timestamp directly from the result of new Date:
Timestamp timestamp = new Timestamp(new Date().getTime());
You can insert the timestamp as a String to the MySQL table. Your String representation in currentTime is sufficient.
The best way to write Timestamp or any data type in Java is to use PreparedStatement and an appropriate method
PreparedStatement ps = conn.prepareStatement("update t1 set c1=?");
ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
ps.executeUpdate();
I am trying to insert a dd/mm/yyyy date format into my database table. The data type for date column in database is date and my SQL insert statement is:
INSERT INTO sm_product(productName, productDescription, productPrice, productQuantity, productStatus)
VALUES ('" + name + "', '" + desc + "', " + price + ", " + quantity + ", 'Available', '" + date + "'";
However, netbeans shows me an error when I added the date variable into the SQL statement.
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 '' at line 1
And it stores the date as:
Wed Jun 19 17:42:26 SGT 2013
And I got my dd/mm/yyyy date format in user interface:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
dateFormat.format(date);
This format is not I wanted. So I wonder how should I amend my SQL statement to fix the problem.
Thanks in advance.
If you are using SQL Server , you can use
REPLACE(CONVERT(VARCHAR(11),date,105),'-','/')
If you insert following format sting into query, record will be updated
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = new Date();
String formatDate = dateFormat.format(date);
I have this MySQL Date data for 6 months in this format:
2010-01-01 to 2010-07-01
But from the UI the ToDate and FromDate are passed in this format:
Jan 1, 2010 and July 1, 2010
Please tell me how can I convert this data into MySQL equivalent format?
First create a SimpleDateFormat for parsing your input from the UI:
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
Next parse an input into a java.sql.Date (which is unfortunately named and different from java.util.Date). So for example:
java.sql.Date date = new java.sql.Date(sdf.parse(fromDate).getTime());
Finally use the date to pass to JDBC when making your database queries. Such as:
Connection con; // assuming you have a database connection
PreparedStatement ps = con.prepareStatement("SELECT * FROM table WHERE x = ?");
ps.setDate(1, date);
ResultSet resultSet = ps.executeQuery();
I formatted my jspinner as:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
JSpinner.DateEditor de = new JSpinner.DateEditor(jSpinner1, "MM/dd/yyyy");
jSpinner1.setEditor(de);
and try to insert the value of jSpinner to ms db:
String SQLString = "INSERT INTO Table1(DateToday)VALUES(?)";
stmt = con.prepareStatement(SQLString);
stmt.setDate(1, new java.sql.Date(sdf.format(jSpinner1.getValue())));
but I still get an error.
Please do me some favor if you could give any sample code to get it right.
Many many thanks...
For SQL Server, you could use a string value
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
....
stmt.setString(1, sdf.format(jSpinner1.getValue()));
but the date should have worked so the error is likely that you have some constraint on the table that is not satisfied.