I am trying to save a timestamp to a SQL DB with the following line inside a PreparedStatement
ps.setTimestamp(5, new Timestamp(ITEM.getModifiedTime().getTime()));
When I debug and inspect the PreparedStatement I can see the date and the time with the Java and SQL types being timestamp but when I look at the DB the field appears like this
2016-08-08 00:00:00.000
How can I get the time to come through? I am using SQL Server 2008
Related
I am trying to insert the timestamp value from oracle to mysql timestamp column.
oracle value is 2017-09-01 11:35:22.495000000 but while getting value from result set its giving 2017-09-01 11:35:22.495.
its stored in oracle using oracle.sql.timestamp and i cannot insert the value in mysql.so getting stringvalue or timestamp value from oracle.sql.timestamp API.
But mysql storing the value is 2017-09-01 11:35:22.000495 and datatype defined as timestamp (6) and am not sure why its inserting the value like this?
How i can store the value in mysql similar to oracle ?
Using JDBC you should be able to directly copy a timestamp from one database to another doing something like this:
try(Connection oracleConnection = getOracleConnection();
Connection mysqlConnection = getMySQLConnection();
PreparedStatement oracleStmt = oracleConnection.prepareStatement("SELECT my_time FROM oracle_table");
PreparedStatement mysqlStmt = mysqlConnection.prepareStatement("INSERT INTO mysql_table VALUES (?)");
ResultSet rs = oracleStmt.executeQuery()) {
while(rs.next) {
mysqlStmt.setTimestamp(1, rs.getTimestamp("my_time"));
mysqlStmt.execute();
}
}
Timestamps are essentially numeric datatypes. Different DBMS's can have different precisions and different ways of handling timezones, but you shouldn't need any database specific API's to interact with them in most cases.
If you need to format a Timestamp you can use SimpleDateFormat on what you get back from getTimestamp() to format the string any way you need to.
I am executing following query in psql via console and getting output :
select details
from history_transactions
,history_operations
where history_operations.transaction_id = history_transactions.id
and type = 3
and created_at >= NOW() - INTERVAL '5 minutes'
However when I call this code from my java program, it is not returning any output. The ResultSet is null. PFB my code:
Connection conn = getConnection();
java.sql.Statement stmt = null;
String sql ="select details from history_transactions , history_operations where history_operations.transaction_id=history_transactions.id and type =3 and created_at >= NOW() - INTERVAL '5 minutes'";
try{
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println("Inside resultset");
}
}
catch(Exception e)
{
e.printStackTrace();
}
Any idea where I am going wrong?
I am not getting any exception as well.
Note: If I change the interval from 5 minute to 6 hours or more it is working and giving me output. If I change the interval < 5 hours then the resultset is null. However If I login to psql server and execute the query as it is in the code. I am getting output.
I am using java version "1.8.0_151" and PostgreSQL JDBC 4.2 Driver, 42.2.1 - as per https://jdbc.postgresql.org/download.html - it is the suitable driver.
The PostgreSQL NOW() function returns a timestamp with time zone value. In order to use that value against a column of type timestamp (without time zone) PostgreSQL needs to implicitly CAST that value to match the column type. However, testing shows that if the client and the server are set to different time zones the result of that CAST can be different when connected via psql vs. when connected via JDBC. For example:
Server time zone: UTC
Client time zone: America/Denver, a.k.a. "MST/MDT", currently UTC-7
When connected via psql,
SELECT CAST(CAST(NOW() AS timestamp) AS varchar)
returns the UTC value
2018-02-05 22:40:25.012933
but when connected via JDBC the same query returns the MST value
2018-02-05 15:40:57.288587
To return the UTC value under JDBC we can execute
set time zone 'UTC'
before running our SELECT query.
I'm using PostgreSQL 8.4, and the server is linux, and the linux's time zone is'EDT' not 'UTC'. The configuration of PostgreSQL make the DataBase's time zone to 'UTC'. The code is running on JBoss9.
I have one sql, select to_char(ts_entry.submitted_date, 'MM/DD/YYYY HH24:MM') as submitted_date_format from ts_entry where ....
If we run the sql in PostgreSQL, we will get the value, "07/10/2017 02:07"
But when I try to get the value from resultSet in java,
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(sql);
String value = rs.getString("submitted_date_format");
The value will be "07/09/2017 22:07".
The origin value in DB is "2017-07-10 02:02:25.268+00".
How can I handle the effect caused by linux server's timezone in code level?
BTW, I know an alternative solution, change the start up scripts of jboss, to make the jboss to start up using timezone 'UTC'. Can this issue be handled in code level?
The Database server machine's time zone has no direct impact on the behaviour, except that it is used to initialize timezone in postgresql.conf, which is the initial setting for the client time zone unless overridden by the database session.
PostgreSQL stores timestamp with time zone in UTC internally and converts it to the client's local time zone upon delivery.
So you should set the database session time zone the way you need with
SET TIME ZONE '<time zone name>';
That will convert dates to that time zone when you select then from PostgreSQL.
I am trying to insert the date using this code:
java.sql.Timestamp sqlNow=new java.sql.Timestamp(new java.util.Date().getTime());
pstTimestamp(1,sqlNow);
On running the code, the result is successful, but the date is not been displayed in the database.
You should use PreparedStatement and use it to set the date as follows :-
PreparedStatement pstmt = con.prepareStatement("INSERT INTO table_name (col_name) VALUES (?)");
pstmt.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
pstmt.executeUpdate();
Read more here
Try this
PreparedStatement ps = con.prepareStatement("INSERT INTO table_name (col_name) VALUES (now())");
ps.executeUpdate();
use now() so that it will get the date in db format only.
Make sure you commit after running the command. Or make sure auto commit is enabled on the connection.
Just you need to provide the java.sql.Timestamp class object to the PreparedStatement object rest of work will be done by driver.
I think there is a problem in your code while setting place holder's value(parameter).
Use pstmnt.setTimestamp(int index, java.sql.Timestamp timestamp_object);
now execute your query as: pstmnt.executeUpdate();
I have a database table in oracle which has a column of type DATE. It looks like the table below
TABLE1
ID PRODUCT_NAME ITEM_CNT ENTERED_DATE
1 prod1 500 2012-07-01
2 prod2 1000 2012-06-30
in my java code, I want to get the total item_cnt for a certain date range. here is the code sample
String sql = "select sum(item_cnt) from table1 where entered_date between ? and ?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try{
conn = getConnection(url, user, passwd);
pstmt = conn.prepareStatement(sql);
pstmt.setDate(1, java.sql.Date.valueOf(from_date)); //from_date is a string of "yyyy-mm-dd"
pstmt.setDate(2, java.sql.Date.valueOf(to_date)); //to_date is a string of "yyyy-mm-dd"
rset = pstmt.executeQuery();
....
}catch(SQLException e){
//do something
} finally{
//clean up
}
This code was running fine for a while until three days ago, I start getting the following exception at line pstmt.executeQuery();
java.sql.SQLRecoverableException: No more data to read from socket
at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1157)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:290)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:884)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1167)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1289)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3584)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3628)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1493)
I tried to search for answers but couldn't find anything that really explains it. then I changed my sql query to
"select sum(item_cnt) from table1 where entered_date between to_date(?, 'yyyy-mm-dd') and to_date(?, 'yyyy-mm-dd')";
and instead of setting date, I changed the prepared statement to the following
pstmt.setString(1, from_date);
pstmt.setString(2, to_date);
Then the exception is gone.
Another confusion is, when I populate my table, I am still using the following
pstmt.setDate(1, java.sql.Date.valueOf(date)); //date is a string of format "yyyy-mm-dd"
and it is still working. only the select statement was giving me exceptions.
Now everything is working but I really want to know why. Anyone knows?
I did upgrade my java to 1.7.0_03-b05 recently. and I am using ojdbc6.jar. The oracle is 11g. Could this be the driver's problem? is ojdbc7 out?
I was facing this exception while working over JDBC with IBM WAS 7.0, I had performed a JCA lifecycle management operation on data source. Which is like controlling the runtime status of the data source. Purge removes the contents of connection pool for the data source. However, in WAS this purging the pool will not affect the ongoing transactions. Check on your side.
Another thing which I performed was; the disk space was full on directory where Oracle was installed, I added extra space over that.
As a best practice, I stay away from java.sql.Date class and use to_date() and to_char() functions while dealing with Dates in Java with Oracle.