how to insert current date in mysql database using jsp? - java

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();

Related

Update query is not working properly with date in where clause from prepared statement

I am trying to update a record using prepared statement(JAVA). This is my code
query = "UPDATE TABLE SET ORDER_ID = ? WHERE CUST_CODE = ? AND ORDER_DATE = ?";
stmt = con.prepareStatement(query);
stmt.setInt(1, 20);
stmt.setString(2, "sk");
stmt.setObject(3, getCurrentTimeStamp('2015-07-18T13:32:56.971-0400'));
stmt.execute();
The getCurrentTimeStamp() is a method that returns OffsetDateTime of given string.
The problem here is that the update query doesn't work fine, and the value is not actually updated. Before and after the update the values or ORDER_ID are same.
There is no issues with the getCurrentTimeStamp() method as I am using it for other DML queries and it works fine. I think I have issues with the update query
Can someone help me with this.
Thanks in advance

JDBC4 insert date "0001-01-01"

I want to insert "0001-01-01" as a value into a date field by using Java PreparedStatement.
But it throws exception when I tried this:
String sql = "insert into mytable values(?)"
ps = conn.prepareStatement(sql);
ps.setDate(1, java.sql.Date.valueOf("0001-01-01"));
ps.executeUpdate(); // throws exceptions here.
The error is :
The supplied value is not a valid instance of data type datetime. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision.
If I don't use PreparedStatement, I can insert "0001-01-01". However,
prepare statement seems not allow me to insert this value.
It will work if I inserted "1969-01-01" instead of "0001-01-01".
Any ideas?
Updates:
Here are more info that might be needed.
we use sql server 2012.
we have to use "0001-01-01" because these values were already there. I am changing some very very old codes to use prepare statement. So I have to insert the same values in the same functionality.
Updates 2:
We are using "date" datatype, not "datetime" datatype.
Based on this https://msdn.microsoft.com/en-us/library/bb630352.aspx, "0001-01-01" is not out of range for "date" field.
In addition, I am able to insert "0001-01-01" to the date field without using prepare statement. i.e.
String sql = "insert into mytable values('0001-01-01')"
java.sql.Statement statement = conn.createStatement();
statement.executeUpdate(sql);
So it is not sql server's problem or db field's problem.
Try using the different suitable JDBC driver.

PreparedStatement

I am using PreparedStatement's setString method to set values for the start and end dates in a sql query.
String sql = "..... " AND tableA.time BETWEEN ? " +
" AND ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, startDate);
st.setString(2, endDate);
The values however are not being set. I understand that normally there is an equals sign:
"tableA.member_id = ?" +"
How do I than call setString method when I am using a 'Between' operator in the sql statement? Hope someone can advise. Thank you.
See http://docs.oracle.com/cd/B28359_01/server.111/b28286/conditions011.htm
"BETWEEN" can be used with datetime data types. However, if tableA.time is a datetime field of some kind (Timestamp, etc.), using st.setString(...) won't work. You need to use setDate(dt) or setTimestamp(ts) instead. See Using setDate in PreparedStatement for more info.
Use setDate.
Is your startDate and endDate a java.util.Date object?
If it is, you can use this code.
st.setDate(1, new java.sql.Date(startDate.getTime()));
st.setDate(2, new java.sql.Date(endDate.getTime()));
If it is not. Convert that first ro java.util.Date object.
BETWEEN expects its arguments to have a type that is compatible with the column being tested. Giving it string arguments for a date column won't work.
You could add a function to the SQL in order to convert the string to a date (I don't know what database you're using, this example uses Oracle's to_date function):
from tableA.time BETWEEN to_date(?, 'yyyy/mm/dd') AND to_date(?, 'yyyy/mm/dd')
Alternatively you could leave the SQL alone and use setDate on the PreparedStatement, like:
setDate(1, new SimpleDateFormat("yyyy/MM/dd").parse(startDate));
This second way is more usual, it has the advantage of avoiding having to add a date-conversion function (that may be non-standard) to your SQL.
But you would have to do the conversion on one side or the other. The database's SQL parser won't convert it for you. If the database took responsibility for the conversion and there was a mistake it could introduce data errors silently, the less error-prone alternative is for the application developer to tell the database how the date string should be converted.

update statement in java - pgAdmin database

It compiles and runs ok, but when I open my table "subscription" in pgAdmin, there is no difference. Should I change something?
pst = con.prepareStatement("UPDATE subscription SET (cancellationdate = ?)"+
"WHERE \"magazineID\"= ?);
Date cancel = new java.sql.Date(System.currentTimeMillis());
pst.setDate(1, cancel);
pst.setInt(2, 4042); //this is a random id that already exist in my db
pst.executeUpdate();
Make sure to:
Commit your Connection
Close your PreparedStatement
Close your Connection
In order to see your changes in your database

java.sql.SQLRecoverableException: No more data to read from socket

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.

Categories

Resources