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());
Related
I want to get the date in DATE column and want to compare with the current date. if the date is less than current date then I want to SET the value of PERMISSION column allow. But my Query doesn't execute.
Which I have tried is given in my below code.
Date date1 = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//current date
Date date = new Date();
date1 = date;
CurrentDate.setText(date1.toString());
String UpdateQuery = null;
String Allow = "allow";
UpdateQuery = "UPDATE company SET permission = '"+Allow+"' WHERE date < ?";
pst = conn.prepareStatement(UpdateQuery);
SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd");
String addDate = CurrentDate.getText();
pst.setString(2, addDate);
pst.executeUpdate();
System.out.println("Updated");
I want to get a value of permission table to SET to "allow" when the update query is executing;
pst.setString(2, addDate);
I think this should be changed to:
pst.setString(1, addDate);
because you only have one parameter in your prepared statement.
Also, when comparing dates, you need to enclose them in single quotes, so changing your UpdateQuery string to
"UPDATE company SET permission = '"+Allow+"' WHERE date < '?' ";
is also a necessary step.
What is the correct format for date filtering - JDBC to SQL
I have been trying to use the following with an MS-Access DB
SELECT doctorbusiness.dateofreport,
doctorbusiness.patientname,
doctorbusiness.labcomm,
doctorbusiness.xcomm,
doctorbusiness.spccomm,
doctorbusiness.ecgcomm
FROM doctorbusiness
WHERE doctorbusiness.doctorname = '"+selectedDoc+"'
AND (( doctorbusiness.dateofreport >= # "+sd+" # )
AND ( doctorbusiness.dateofreport <= # "+ed+" # ))
selectedDoc is in String and sD and eD in date format.
The query runs fine in MS-Access but gives the following exception :
net.ucanaccess.jdbc.UcanaccessSQLException: unknown token:
UPDATE
public void printDoctorIncome() {
Date startDate = easypath.docB_startDate_jxdp.getDate();
Calendar calSD = Calendar.getInstance();
calSD.setTime(startDate); // convert your date to Calendar object
int daysToDecrement = -1;
calSD.add(Calendar.DATE, daysToDecrement);
Date real_StartDate = calSD.getTime();
SimpleDateFormat sdF1 = new SimpleDateFormat("dd-MM-yyyy");
String sD = sdF1.format(real_StartDate);
JOptionPane.showMessageDialog(null, sD);
Date endDate = easypath.docB_endDate_jxdp.getDate();
Calendar calED = Calendar.getInstance();
calED.setTime(endDate); // convert your date to Calendar object
int daysToIncrement = +1;
calED.add(Calendar.DATE, daysToIncrement);
Date real_endDate = calED.getTime();
SimpleDateFormat sdF2 = new SimpleDateFormat("dd-MM-yyyy");
String eD = sdF2.format(real_endDate);
JOptionPane.showMessageDialog(null, eD);
String selectedDoc = easypath.drname_jlist.getSelectedValue().toString();
String sql = "SELECT doctorBusiness.dateofreport, doctorBusiness.patientName, doctorBusiness.labComm, doctorBusiness.xComm, doctorBusiness.spcComm, doctorBusiness.ecgComm FROM doctorBusiness WHERE doctorBusiness.doctorname ='"+selectedDoc+"' AND (doctorBusiness.dateofreport >= ?"+sD+"? AND doctorBusiness.dateofreport <= ?"+eD+"?)";
try {
conn = connectDB.getConnection();
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
doctorIncome.docIncomePrint_table.setModel(DbUtils.resultSetToTableModel(rs));
doctorIncome dI = new doctorIncome();
dI.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
}
This is the code I am using
With JDBC better way to do it is use setDate/Time/Timestamp methods of PreparedStatement. And you shouldn't care about concrete DB's date format.
Date dateFrom = ...
Date dateTo = ...
String sql = "... where myDate >= ? and myDate <= ? "
preparedStatement.setDate(1, dateFrom);
preparedStatement.setDate(2, dateTo);
Using a PreparedStatement is a good idea. But you can also use either #MM/dd/yyyy# or #yyyy-MM-dd# (with or without hours:minutes:seconds).
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
hi i have to convert timestamp to date after check the query and return the count value.
my database have date(1344399208,1344399269),status(Q,Q).
This is my code:
public class GetCurrentDateTime {
public int data(){
int count=0;
java.sql.Timestamp timeStamp =new Timestamp(System.currentTimeMillis());
java.sql.Date date = new java.sql.Date(timeStamp.getTime());
System.out.println(date);
//count++;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date=CURDATE()");
ResultSet result = statement.executeQuery();
while(result.next()) {
// Do something with the row returned.
count++; //if the first col is a count.
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return count;
}
}
Here the date is saved in timestamp format.but i like to convert date(yyyy-mm-dd) format.its done successfully.ya i got the output is 2012-08-08.but i have to check the query today date+status=Q .so how is that date is save in variable and call that variable in query.so how is wrote query for above condition.after check the condition and display the returns count value on my tomcat console.How is to do.please help me
Partial Answer to your Question
Date Examples
Examples borrowed from Code Ranch and SO posts
// Get system time
Timestamp SysTime = new Timestamp(System.currentTimeMillis());
java.util.Date UtilDate = new java.util.Date(Systime.getTime());
java.sql.Date SQLDate = new java.sql.Date(Systime.getTime());
// Date + Time + Nano Sec
System.out.println(SysTime);
// Date + Time
System.out.println(UtilDate);
// Date
System.out.println(SQLDate);
Formatting Dates
// Apply Format
Date InDate = SQLDate; // or UtilDate
DateFormat DateFormat = new SimpleDateFormat("yyyy MM dd");
String DisplayDate = DateFormat.format(InDate);
System.out.println(DisplayDate);
Please note that I am new to java, hence verify if it works.
Comparing dates
See this SO post:
How to compare dates using Java
To convert date to the date format specified:
int timestamp = 1231342342342; // replace with timestamp fetched from DB
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
String dateString = sdf.format(date); //convert to yyyy-mm-dd format
From what I understand from the edit, you want the query to be something like this:
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date='"+dateString+"'");
I'm assuming that the date is stored in string format in the DB since you asked it to be converted into a particular format.
From comments:
To get midnight date:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
To get all entries within a 24 period:
"select * from xcart_orders where status='Q' AND date between " + cal.getTimeInMillis() + " and " + (cal.getTimeInMillis() + 86400000l);
My database column datatype is timestamp. How do I insert the current date and time using a PreparedStatement or Statement?
I have tried this:
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
pstmt.setDate(9, new java.sql.Timestamp(date.getTime()));
But the value inserted in the table is 1328847536746. This not right, i am using sqlite
There is a separate Timestamp value class in java.sql.
pstmt.setTimeStamp(9, new java.sql.Timestamp(date.getTime()));
The javadoc explains:
public class Timestamp
extends Date
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.
Use setTimestamp().
pstmt.setTimestamp(9, Timestamp.valueOf("2002-03-13 11:10:15.01"));
This is the code I've used so far to get it done
Timestamp nextRunTimestamp = null;
if(endDate != null || !endDate.equalsIgnoreCase(""))
{
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.parse(endDate);
Calendar tempDate = dateFormat.getCalendar();
tempDate.set(Calendar.HOUR, nextRunTime.get(Calendar.HOUR));
tempDate.set(Calendar.MINUTE, nextRunTime.get(Calendar.MINUTE));
tempDate.set(Calendar.SECOND, nextRunTime.get(Calendar.SECOND));
tempDate.set(Calendar.MILLISECOND, nextRunTime.get(Calendar.MILLISECOND));
if(nextRunTime.before(tempDate) || nextRunTime.equals(tempDate))
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
}
else
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
statement.setTimestamp(2, nextRunTimestamp);
statement.setInt(3, result.getInt("id"));
statement.executeUpdate();
DateFormat df = new SimpleDateFormat(yyyy/MM/dd HH:mm:ss); // any Date format
System.out.println("Current Date : " + df.format(new Date()));
pstmt.setDate(9, to_timestamp(df.format(new Date()),'YYYY/MM/DD HH24:MI:SS'));
Here you can use TO_DATE('todayDate', 'YYYY/MM/DD HH24:MI:SS') or
TO_TIMESTAMP('todayDate', 'YYYY/MM/DD HH24:MI:SS')