Using timestamp with mysql and java - 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'.

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

Mysql between dates is not working

I'm writing the below query to get records between two dates. I'm using Mysql version 5.5. May its duplicate exactly I didn't know. But no answer working for me so that I'm asking. I'm following least date after latest date. Even though its not working.
Problem: Empty resultset.
pstmt=con.prepareStatement("SELECT urlid FROM youtubevideos WHERE lastwatched >=? AND lastwatched <=? order by id desc LIMIT 8");
pstmt.setString(1,previousdate);//14-05-2015
pstmt.setString(2,currentdate);//12-08-2015
rs=pstmt.executeQuery();
while(rs.next())
{
.........
}
But I'm getting empty resultset.
My table youtubevideos contains records
urlid lastwatched
-------------------
url1 12-08-2015
url2 11-08-2015
url3 08-05-2015
url4
url5 10-08-2015
Above is some data. Here lastwatched is of varchar and lastwatched is empty for some records. If my previous date 08-05-2015 means less than the current day (12) then above query working. Otherwise (from 13-05-2015 onwards) its not working. Any suggestions please.
You are using wrong date format for sql:
12-08-2015 // this is the output format
use yyyy-MM-dd instead:
2015-08-12 // this is the sql store format
This query works great in my Mysql database:
SELECT * FROM your_table where DATE <= "2015-05-08" AND DATE >= "2015-08-12"
To convert your strings:
Date initDate = new SimpleDateFormat("dd-MM-yyyy").parse(date);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String parsedDate = formatter.format(initDate);
Here lastwatched is of varchar
The issue is that you are storing date fields as type VARCHAR. This would work if your date format was Y-m-d since sorting this alphabetically is the same as sorting by date.
I recommend you change the lastwatched column to be a date type, this will allow the BETWEEN to work correctly and will also provide access to the date functions in MySQL.
Fix the data in the table. You should not be storing bona fide dates as varchar(). MySQL has a great data type for them, called date (or perhaps datetime.
Here is one method:
alter table youtubevideos add column NEW_lastwatched date;
update youtubevideos
set NEW_lastwatched = str_to_date(lastwatched, '%d-%m-%Y');
alter table drop column lastwatched;
alter table rename column NEW_lastwatched lastwatched date;
Then, pass in your parameters in the ISO standard format 'YYYY-MM-DD' and your problems with dates using this column will be fixed.

SQL SELECT and timestamp columns

In my application i have a java Timestamp dateCreated, which is inserted to a mysql Timestamp colum. Inserting is no problem, i use a prepared statement and statement.setTimestamp(dateCreated).
Now i need to select a row with the dateCreated as unique identifier. my method gets another java Timestamp object.how does the SQL query work in this case? i havent figured out how to compare the java timestamp to the mysql one.
SELECT * FROM table WHERE timestamp_column = ???
Thanks!
In Java you will use a similar setTimestamp method as you did with the insert.
Timestamp t = ???;
String sql = "SELECT * FROM table WHERE timestamp_column = ?";
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setTimestamp(t);
etc.

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