PreparedStatement and DateTime - java

I am trying to use DateTime from the Joda library and I realized that PreparedStatements doesn't support DateTime. What can I do instead? I can set TimeStamp but that's not really what I want. Is there a workaround or do I have to use TimeStamp? In my MySQL database I have also chosen DateTime as the type.
DatabaseConnection dbConnect = new DatabaseConnection();
PreparedStatement query =dbConnect.getConnect().prepareStatement(sql);
query.setInt(1, c.getMemberId());
query.setDateTime(2, c.getStartDate());
query.setDateTime(3, c.getEndDate());

setDate(java.sql.Date) seems like what you're looking for:
query.setDate(2, new java.sql.Date(c.getStartDate().getMillis());

In your PreparedStatement, call the toDate() method on your DateTime objects.
If you are not interested in times, you might as well change your database columns to DATE.

Related

Storing java.sql.Timestamp type into HSQL database

We do have multiple databases for our application.
The date of type java.sql.Timestamp is being stored in DATETIME data type of SQL SERVER.
But
For storing same type in HSQL DB, I am using TIMESTAMP, and it is not able to cast it.
I will not be able to change in java code because it is working in SQL Server and Oracle both, but I need casting in hsql query only.
Current working query with SQL Server with datetime field is:
insert into SYSTEM_DOCUMENTS values(?)
Java code:
timeStamp=new java.sql.Timestamp(new java.util.Date().getTime());
String q="insert into SYSTEM_DOCUMENTS values(?)";
pstm = con.prepareStatement(q);
pstm.setTimestamp(1, timeStamp);
pstm.executeQuery();
If you're using Hibernate it can be simple by adding #Temporal annotation
#Temporal(TemporalType.DATE)
private Date date;
Temporal has TIMESTAMP, DATE, TIME enums

Using timestamp with mysql and java

I'm trying to save a timestamp to a table in mySQL but whenever I look at the results it just shows 0000-00-00 00:00:00.
I assume I'm not using the timestamp right but anyways in my table I have a column named time and its property is TIMESTAMP
In my Java I have:
java.sql.Timestamp timestamp = new java.sql.Timestamp(0);
String query = "insert ignore into time(time_now) values (?)";
pstmt.setString(1, timestamp);
pstmt.executeUpdate();
My database connection is fine as I have a lot of other information that's being uploaded to it with no problem, I'm just having trouble with the timestamp
Something like this should work:
java.util.Date date = new java.util.Date();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("insert ignore into time(time_now) values (?)");
preparedStatement.setTimestamp(1, timestamp);
If you only want to store the time then use the TIME data type instead and to insert the current time of the SQL server use CURTIME() like this
insert into your_table (time_column)
values (curtime())
Take a look at java.sql.Timestamp. You are instantiating a new Timestamp object with '0'.

Timestamp issue from ojdbc5 & ojdbc

JVM Timezone details : India Standard TimeAsia/Calcutta019800000
DB Timezone details : Central Standard TimeAmerica/Chicago3600000-21600000
Sample Code:
String sql = "select systimestamp as base from dual";
....
PreparedStatement stmt = con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
System.out.println(rs.getTimestamp("base"));
System.out.println(rs.getString("base"));
}
Test-1:
I tested using ojdbc14.jar 10.1.0.3.0 with, it works as expected printing the db time
Output:
2013-12-05 01:23:57.141583
2013-12-5 1.23.57.141583000 -6:0
Test-2:
I tested using ojdbc5.jar & ojdbc6.jar 11.2.0.3.0 with, getTimestamp print local time where as getString prints db time.
Output:
2013-12-05 12:57:54.3508
2013-12-05 01:27:54.3508 -6:00
Please suggest what is wrong with Test-2 ojdbc driver version 11.2.0.3.0 where the getTimestamp() prints local time. My application expect the db time like Test-1 in the getTimestamp() where it matches with DB timestamp.
We had the same issue a few days ago at my company. The bottom line of this is you should never get a timestamp as a string (as it's database/driver specific) and always get the TimeStamp object and format it any way you want using a SimpleDateFormat.
And it's always worth mentioning that the Timestamp class is an abomination , from the javadocs
Due to the differences between the Timestamp class and the
java.util.Date class mentioned above, it is recommended that code not
view Timestamp values generically as an instance of java.util.Date.
The inheritance relationship between Timestamp and java.util.Date
really denotes implementation inheritance, and not type inheritance.

Set timestamp in Oracle

I use Prepared statements in Oracle SQL query. I have problem which I don't know how to solve.
I want to set timestamp like using this:
ps.setTimestamp(36, null);
The problem is that I don't know what parameter to set in order to execute timestamp into Oracle? How I must replace null in my case?
This example sets a Timestamp value to the current time (with precision to milliseconds):
Timestamp ts = new Timestamp(new Date().getTime());
ps.setTimestamp(36, ts);
If you also need nanoseconds you can set those separately:
Timestamp ts = new Timestamp(new Date().getTime());
ts.setNanos(12345);
ps.setTimestamp(36, ts);
If you look at the method in the PreparedStatement class, you need to create a TimeStamp object that you will replace your null with.

java.sql.SQLException: ORA-01843: not a valid month

I am getting the following error when inserting data into my oracle database.
java.sql.SQLException: ORA-01843: not a valid month
In database date is as: dd-MMM-yy (06-MAR-12)
I am converting 06-03-2012 to dd-MMM-yy by the following method:
String s="06-03-2012";
String finalexampledt = new SimpleDateFormat("dd-MMM-yy").format(new SimpleDateFormat("dd-MM-yyyy").parse(s));
So i got 06-Mar-12 which is same as the above database date format still i am getting the error. I am inserting as:
in index.jsp
String todaydate="";
Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
todaydate = dateFormat.format(calendar1.getTime());
<input type="text" name="datename" value="<%=todaydate%>"/>
in servlet(doPost)
String s=request.getParameter("datename");
PreparedStatement ps=con.prepareStatement("insert into tablename(rest_dt, othercolname) values (to_date(?, 'dd-mm-yyyy'), ?)");
ps.setString(1, s);
ps.setString(2, otherstringdata);
int rs=ps.executeUpdate();
Any idea please
so make
("insert into mytablename (rest_dt) values to_date(?, 'DD-MM-YYYY')");
Try this
TO_DATE(?, 'DD-MM-YYYY','NLS_DATE_LANGUAGE = American')
// gets from Oracle docs
The datatype of your rest_dt columns is a DATE, so you need to supply one. You can use the TO_DATE function to convert a string to an Oracle DATE, so your insert statement
insert into tablename(rest_dt, othercolname) values (to_date(?, 'dd-mm-yyyy'), ?)
is fine.
Just make sure the string value you bind to your first ?-variable is in the format dd-mm-yyyy. And don't convert or format that value yourself: the TO_DATE function does that part.
There is no need to anything about session settings like nls_date_language here, since you have wisely chosen to use a language agnostic setting for the month with your MM mask (instead of MON).
Regards,
Rob.
Problem is that oracle uses NLS_DATE_LANGUAGE to get the current name of the month. So you should do
select * from nls_session_parameters
and check if you have the correct values. You can also check with the following select which name you get for the month
select TO_CHAR(TO_DATE('01-03-01', 'DD-MM-YY'), 'MON') from dual
I really don't understand why you insert the variable as a string value. Just use a date type (do the conversion on the client) in java and insert it without converting. If you really want to insert it as a string I would use a conversion to something like dd-MM-yyyy and insert it with TO_DATE(, 'DD-MM-YYYY').
Edit:
Do the conversion of the date on the client and use
ps.setDate(2, <yourDate>);
The same issue faced while running big query (multiple union) in Java and issue not with actual input since I have properly converted the with to_date('30-06-2021', 'dd-MM-yyyy') and found issue is with the date1 in query.
e.g.
select a,b,c from table1 where date1='31/12/2015'and date2=<actual input>
union
select a,b,c from table2 where date1='31/12/2015'and date2=<actual input>
union
select a,b,c from table3 where date1='31/12/2015'and date2=<actual input>
.
.
date1 also should be convert to to_date like below
e.g.
select a,b,c from table1 where date1=to_date('31/12/2015', 'dd-MM-yyyy') and date2=<actual input>
Hence issue resolved. My suggestions is, if you are getting such issues check the date part in the query and mention with to_date.
Java code:
#Autowired
private NamedParameterJdbcTemplate namedJdbcTemplate;
List<ResponseDTO> list = new ArrayList<>();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("value1", dto.getValue1());
params.addValue("value2", dto.getValue2());
list = namedJdbcTemplate.query(SQL_QUERY, params, new CustomValueMapper());
Its purely only my own experience. Click up vote if it helps.
java.time and JDBC 4.2
Don’t transfer a date as a string to or from your database. Transfer a proper date object. I am assuming that your JDBC driver is at least JDBC 4.2 compliant. About all drivers are these days. In this case LocalDate is the type to use for dates, both in your Java program and in the transfer to the database.
So what you basically need is this:
LocalDate date = LocalDate.of(2012, Month.MARCH, 6);
PreparedStatement ps = con.prepareStatement(
"insert into tablename(rest_dt, othercolname) values (?, ?)");
ps.setObject(1, date);
ps.setString(2, otherstringdata);
int rs = ps.executeUpdate();
If you are receiving your date as string input from JSP, immediately parse it into a LocalDate object. There’s no need to wait until you need to put it into your database.
String inputString = "06-03-2012"; // Meaning 6 March 2012
LocalDate date = LocalDate.parse(inputString, DATE_PARSER);
I have been using this formatter:
private static final DateTimeFormatter DATE_PARSER
= DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ROOT);
Links
Oracle tutorial: Date Time explaining how to use java.time.
Related question: Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2

Categories