I am reading few data from a text file using java code,along with date in format (30-OCT-2012 12-22-44-991) and i want to store these details in Oracle Database but in the same format as used by oracle.
I tried To_date but of no use, it gives error.
Kindly help me.
Use SimpleDateFormat in Java to parse your String to a java.util.Date. Then use a PreparedStatement and set the date on that.
Edit:
You can use a PreparedStatement like Aleksander Blomskøld already suggested and with help from Using Oracle to_date function for date string with milliseconds:
final sql = "INSERT into IFT_VEHICLE_STATUS (LATITUDE, LONGITUDE, UPDATED_AT) " +
"VALUES (?, ?, to_timestamp(?, 'DD.MM.YYYY HH24:MI:SS:SSFF3'))";
final PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 81000000);
pstmt.setInt(2, 162000000);
pstmt.setDate(3, oracleDate);
pstmt.execute();
Old:
Are you trying to convert a java.util.Date into a java.sql.Timestamp? You could do that like this:
try {
final Date javaUtilDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-01-20 11:46:06");
System.out.println("javaUtilDate = " + javaUtilDate);
final Timestamp oracleDate = new Timestamp(javaUtilDate.getTime());
System.out.println("oracleDate = " + oracleDate);
} catch (ParseException e) {
e.printStackTrace();
}
This will give the following output:
javaUtilDate = Fri Jan 20 11:46:06 CET 2012
oracleDate = 2012-01-20 11:46:06.0
Related
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat ("dd/MM/yy");
String date = df.format(today);
System.out.println(date);
PreparedStatement sql = con.prepareStatement("select count(*), name, status from tablename where file_date = date group by name, status");
ResultSet rs = sql.executeQuery();
However, the sysdate format in SQL is dd/MM/yy
But the date format in Eclipse is yyyy-MM-dd HH:mm:ss.fff
How do I convert it in query so that I can get dd/MM/yy format?
What about passing a true SQL Date, don't bother about internal string representation for dates.
PreparedStatement sql = con.prepareStatement("select count(*), name, status from tablename where file_date = ? group by file_name, status");
sql.setDate(1, new java.sql.Date(new java.util.Date().getTime());
I have the following column value which I am converting and storing in another column
Nov 22 2014 00:00:00 AM
Now I am using the following query to convert it to Date format and store in another column
UPDATE DataNov2014 SET Datee = str_to_date(Date,'%d %b %Y %H:%i:%s');
But I am getting the following exception
Exception in thread "main" java.sql.SQLException: Incorrect datetime
value: 'Nov 22 2014 00:00:00 AM' for function str_to_date
Is there any mistake in my query/date format ??
Any help would be appreciated, Thanks
tyr this
UPDATE DataNov2014 SET Date= to_char(Date,'mon dd yyyy mm:ss:hh');
I suggest you use a PreparedStatement and a Date bind parameter. Also, you can use try-with-resources. Putting it all together, something like
String sql = "UPDATE DataNov2014 SET Datee = ?";
DateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
try (PreparedStatement ps = conn.prepareStatement(sql)) {
Date theDate = sdf.parse("11-22-2014 00:00:00");
ps.setDate(1, new java.sql.Date(theDate.getTime()));
int count = ps.executeUpdate();
if (count > 0) {
System.out.printf("Query updated %d rows.%n", count);
} else {
System.out.println("Query didn't update any rows");
}
} catch (Exception e) {
e.printStackTrace();
}
Assumes your field Datee datatype is Datetime
UPDATE DataNov2014 SET Datee = str_to_date('Nov 22 2014 00:00:00 AM','%M %d %Y %H:%i:%s');
Date dateformat=null;
Date i5Date=null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String date = i5t1.getText();
i5Date=(Date) formatter.parse(date);
while(rs.next())
{
rs.moveToInsertRow();
rs.updateDate("Date",i5Date);
rs.insertRow();
}
This doesnt update the resultset in date format. May i know what changes i have to make to update the resultset in date format. (Note : - I dont want to update in string format.)
Note: - i have made the connections and the resultset is opened.
The date in result set is a java.sql.Date type. You are trying to format java.util.Date.
You need to convert between them to get this to work assuming you are just rendering the date.
If not you need to make the change directly to your schema. See these SO posts:
ResultSet.getTimestamp("date") vs ResultSet.getTimestamp("date", Calendar.getInstance(tz))
java.util.Date vs java.sql.Date
Update
To retrieve between dates like you are trying to do, you need to do:
Connection conn = null;
PreparedStatement pstmt = null;
conn = getConnection();
String query = "select * from table_name between ? and ?";
pstmt = conn.prepareStatement(query);
pstmt.setDate(1, new java.sql.Date(startDate.getTime()));
pstmt.setDate(2, new java.sql.Date(endDate.getTime()));
ResultSet resultSet = pstmt.executeQuery();
I am trying to insert a value in the postgres table through Java . Column type is timestamp.
The code is like this :
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String gameStartedTime = format.format(new Date());
String query= "UPDATE gameStatus g SET g.status ='" + gameStatus
+ g.gameStartTime= to_date('"
+ gameStartedTime + "','yyyy-MM-dd HH:mm:ss')"
// Doesn't matter much
+ " WHERE g.status = 'STARTED' AND " + "g.condition="+ game.getCondition();
Now when I try to execute this statement it fails I get the message like this :
ERROR: conflicting values for "mm" field in formatting string.
DETAIL: This value contradicts a previous setting for the same field type.
I am not sure what is going wrong !!
Any help on this will be useful.
Thanks in advance.
-JE
mm is always the month for the to_date() function. There is no difference between mm and MM (unlike in Java's SimpleDateFormat).
You need to use mi for the minutes.
A full list of all patterns is available in the manual: http://www.postgresql.org/docs/current/static/functions-formatting.html#FUNCTIONS-FORMATTING-DATETIME-TABLE
But you shouldn't use "dynamic" SQL in the first place. It's better to use a PreparedStatement, java.sql.Timestamp and setTimestamp() instead. That relief you from any formatting problems and protect you against SQL injection.
do like this.
java.sql.Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());
this.date = timestamp;
Then add this.date into database..
try it:
ps.setTimestamp(position, new Timestamp(System.currentTimeMillis()));
Try to split the date part from the query and try to compare these values.
It appears (at least from where I see) that the mm which stand for minutes,
does not comply with g.gameStartTime= to_date.
If you pull this part outside the query you can check the values, maybe you will find what the problem is there.
This way works for me using current time:
String query = "INSERT INTO table1 (id,t) VALUES (?, ?)";
//update table1 set t=? where id=?
Connection con = null;
PreparedStatement ps = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setLong(1, 1234); // update ps.setLong(2, 1234);
Calendar cal = Calendar.getInstance();
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
ps.setTimestamp(2,timestamp); // ps.setTimestamp(1,timestamp);
int out = ps.executeUpdate();
if(out !=0){
System.out.println("Record saved");
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Or, you can establish a specific timestamp by using these lines:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.MONTH, 0); // 0 january
cal.set(Calendar.DAY_OF_MONTH, 26);
cal.set(Calendar.HOUR_OF_DAY, 10);
cal.set(Calendar.MINUTE, 47);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
I'm using a database in my Java project and I want to store date in it, the 5th and the 6th parameter are Date Object. I used the solution below but I have errors in the indicated lines:
PreparedStatement creerFilm = connecteur.getConnexion().prepareStatement(
"INSERT INTO FILM (ID, REF, NOM, DISTRIBUTEUR, DATEDEBUT, DATEFIN) "+
"VALUES (?, ?, ?, ?, ?, ?)");
creerFilm.setInt(1, getId());
creerFilm.setString(2, getReference());
creerFilm.setString(3, getNomFilm());
creerFilm.setString(4, getDistributeur());
// These next two lines
creerFilm.setDate(5, new Date (getDateDebut().getDate()));
creerFilm.setDate(6, new Date (getDateFin().getDate()));
// The above two lines
creerFilm.executeUpdate();
creerFilm.close();
Can you help me to fix that please ?
Thank you
I can't really tell from your code, but you have to use java.sql.Date, not java.util.Date.
Here's how you convert from a utility date instance to an SQL date instance:
java.sql.Date date = new java.sql.Date(utilDate.getTime());
I think detailed answer you can read here: How to insert date in sqlite through java
In a short, you can insert Date as setString (or setInt, or setLong (see the above link), but not setDate):
PreparedStatement ps = connection.prepareStatement(<your sql>);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ps.setString(1, df.format(<your date>));