Java : Insert query-Exception - java

I have a doubt regarding database operation.I have one insert query that should run for 10 times. the loop starts and inserted 4 or 5 val while inserting 6th, the db connection got failed for a while and again connected. then what will happen,
whether it skips that particular val or throws exception or roll back th entire operation?
EDIT : Sample Code
try
{
String sql_ji_inser="insert into job_input values (?,?)";
PreparedStatement pst_ji_inser=OPConnect.prepareStatement(sql_ji_inser);
for(int i=0;i<v_new_data.size();i++)
{
Vector row=new Vector();
row=(Vector)v_new_data.get(i);
job_id=Integer.parseInt(row.get(0).toString());
item_no=Integer.parseInt(row.get(1).toString());
pst_ji_inser.setInt(1,job_id);
pst_ji_inser.setInt(2,item_no);
pst_ji_inser.addBatch();
}
System.out.println("No of rows inserted"+pst_ji_inser.executeBatch().length);
}
catch(Exception ex)
{
System.out.println("********Insert Exception*********************");
ex.printStackTrace();
return false;
}
Is this the right way
try
{
int count=0;// for checking no of inserting values
OPConnect.setAutoCommit(false);
String sql_ji_inser="insert into job_input values (?,?)";
PreparedStatement pst_ji_inser=OPConnect.prepareStatement(sql_ji_inser);
for(int i=0;i<v_new_data.size();i++)
{
job_id=Integer.parseInt(row.get(0).toString());
item_no=Integer.parseInt(row.get(1).toString());
pst_ji_inser.setInt(1,job_id);
pst_ji_inser.setInt(2,item_no);
pst_ji_inser.addBatch();
count++;
}
int norowinserted=pst_ji_inser.executeBatch().length;
if(count==norowinserted)
{
OPConnect.commit();
}
}
catch(Exception ex)
{
System.out.println("********Insert Exception*********************");
OPConnect.rollback();
ex.printStackTrace();
return false;
}

That depends on how you're inserting the rows. If you're inserting them in a single transaction on a connection which has auto-commit turned off by connection.setAutoCommit(false) and you're commiting the connection after completing the insert queries using connection.commit() and you're explicitly calling connection.rollback() inside the catch block, then the entire transaction will be rolled back. Otherwise, you're dependent on environmental factors you have no control over.
See also:
When to call rollback?
Update: here's a rewrite of your code. Note that the connection and statement should be declared before the try, acquired in the try and closed in the finally. This is to prevent resource leaking in case of exceptions.
String sql = "insert into job_input values (?, ?)";
Connection connection = null;
PreparedStatement statement = null;
try {
connection = database.getConnection();
connection.setAutoCommit(false);
statement = connection.prepareStatement(sql);
for (List row : data) {
statement.setInt(1, Integer.parseInt(row.get(0).toString()));
statement.setInt(2, Integer.parseInt(row.get(1).toString()));
statement.addBatch();
}
statement.executeBatch();
connection.commit();
return true;
} catch (SQLException e) {
if (connection != null) try { connection.rollback(); } catch (SQLException logOrIgnore) {}
e.printStackTrace();
return false;
} finally {
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
I am by the way not a fan of returning a boolean here. I'd just make the method void, let the catch throw e and put the calling code in a try-catch.

Related

Closes connection and creates a new one not to exceed max cursors after 295 inserts

A previous developer left this message in code.
It runs create statement and execute query and after 295 records it creates new connection.
Following is java code:
private void dbUpdate() throws SQLException, Exception {
Statement st = null;
String sql = "";
int count = 0;
try {
getNewConnection();
conn.setAutoCommit(false);
for (Iterator it = sqlList.iterator(); it.hasNext();) {
if (count < 295) { //Closes connection and creates a new one so as not to exceed max cursors
count++;
} else {
st.close();
conn.close();
getNewConnection();
count = 0;
}
sql = (String) it.next();
// System.out.println(sql + " insert count=" + count);
st = conn.createStatement();
try {
st.executeQuery(sql);
} catch(Exception ex) {
Logger.getLogger(LoadMain.class.getName()).log(Level.SEVERE, sql);
Logger.getLogger(LoadMain.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
sb.append("\n").append("Error SQL:" + sql + "|LocalizedMessage:" +ex.getLocalizedMessage());
}
}
} catch (SQLException ex) {
Logger.getLogger(LoadMain.class.getName()).log(Level.INFO, sql);
Logger.getLogger(LoadMain.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
throw new SQLException(ex);
} catch (Exception ex) {
// Logger.getLogger(loadMain.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
throw new Exception(ex);
} finally {
try {
st.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(LoadMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Is there any logic behind re connection?
(Also developer set autocommit false but not seen committing or roll-backing but only st.close() methods.)
Could anyone please enlighten
Seems as the developer tried to implement connection pooling, which now can be integrated easily with DBCP/Hikari/other database connection pool.
You don't need to commit on DAO level/method, for example
if the code is called by a method with #Transactional or commit is handled on service level.
Also you can't rely that close will commit or rollback, there can be different results with different oracle drivers
According to the javadoc, you should try to either commit or roll back before calling the close method. The results otherwise are implementation-defined.

Resource management in bluemix and explicit closure of prepared statements in JDBC [duplicate]

It is said to be a good habit to close all JDBC resources after usage. But if I have the following code, is it necessary to close the Resultset and the Statement?
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = // Retrieve connection
stmt = conn.prepareStatement(// Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
try { if (conn != null) conn.close(); } catch (Exception e) {};
}
The question is if the closing of the connection does the job or if it leaves some resources in use.
What you have done is perfect and very good practice.
The reason I say its good practice... For example, if for some reason you are using a "primitive" type of database pooling and you call connection.close(), the connection will be returned to the pool and the ResultSet/Statement will never be closed and then you will run into many different new problems!
So you can't always count on connection.close() to clean up.
Java 1.7 makes our lives much easier thanks to the try-with-resources statement.
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement.executeQuery("some query")) {
// Do stuff with the result set.
}
try (ResultSet resultSet = statement.executeQuery("some query")) {
// Do more stuff with the second result set.
}
}
This syntax is quite brief and elegant. And connection will indeed be closed even when the statement couldn't be created.
From the javadocs:
When a Statement object is closed, its
current ResultSet object, if one
exists, is also closed.
However, the javadocs are not very clear on whether the Statement and ResultSet are closed when you close the underlying Connection. They simply state that closing a Connection:
Releases this Connection object's
database and JDBC resources
immediately instead of waiting for
them to be automatically released.
In my opinion, always explicitly close ResultSets, Statements and Connections when you are finished with them as the implementation of close could vary between database drivers.
You can save yourself a lot of boiler-plate code by using methods such as closeQuietly in DBUtils from Apache.
I'm now using Oracle with Java. Here my point of view :
You should close ResultSet and Statement explicitly because Oracle has problems previously with keeping the cursors open even after closing the connection. If you don't close the ResultSet (cursor) it will throw an error like Maximum open cursors exceeded.
I think you may encounter with the same problem with other databases you use.
Here is tutorial Close ResultSet when finished:
Close ResultSet when finished
Close ResultSet object as soon as you finish
working with ResultSet object even
though Statement object closes the
ResultSet object implicitly when it
closes, closing ResultSet explicitly
gives chance to garbage collector to
recollect memory as early as possible
because ResultSet object may occupy
lot of memory depending on query.
ResultSet.close();
If you want more compact code, I suggest using Apache Commons DbUtils. In this case:
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = // Retrieve connection
stmt = conn.prepareStatement(// Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
No you are not required to close anything BUT the connection. Per JDBC specs closing any higher object will automatically close lower objects. Closing Connection will close any Statements that connection has created. Closing any Statement will close all ResultSets that were created by that Statement. Doesn't matter if Connection is poolable or not. Even poolable connection has to clean before returning to the pool.
Of course you might have long nested loops on the Connection creating lots of statements, then closing them is appropriate. I almost never close ResultSet though, seems excessive when closing Statement or Connection WILL close them.
Doesn't matter if Connection is poolable or not. Even poolable connection has to clean before returning to the pool.
"Clean" usually means closing resultsets & rolling back any pending transactions but not closing the connection. Otherwise pooling looses its sense.
The correct and safe method for close the resources associated with JDBC this (taken from How to Close JDBC Resources Properly – Every Time):
Connection connection = dataSource.getConnection();
try {
Statement statement = connection.createStatement();
try {
ResultSet resultSet = statement.executeQuery("some query");
try {
// Do stuff with the result set.
} finally {
resultSet.close();
}
} finally {
statement.close();
}
} finally {
connection.close();
}
I created the following Method to create reusable One Liner:
public void oneMethodToCloseThemAll(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
if (!resultSet.isClosed()) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
if (!statement.isClosed()) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
if (!connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I use this Code in a parent Class thats inherited to all my classes that send DB Queries. I can use the Oneliner on all Queries, even if i do not have a resultSet.The Method takes care of closing the ResultSet, Statement, Connection in the correct order. This is what my finally block looks like.
finally {
oneMethodToCloseThemAll(resultSet, preStatement, sqlConnection);
}
With Java 6 form I think is better to check it is closed or not before close (for example if some connection pooler evict the connection in other thread) - for example some network problem - the statement and resultset state can be come closed. (it is not often happens, but I had this problem with Oracle and DBCP). My pattern is for that (in older Java syntax) is:
try {
//...
return resp;
} finally {
if (rs != null && !rs.isClosed()) {
try {
rs.close();
} catch (Exception e2) {
log.warn("Cannot close resultset: " + e2.getMessage());
}
}
if (stmt != null && !stmt.isClosed()) {
try {
stmt.close();
} catch (Exception e2) {
log.warn("Cannot close statement " + e2.getMessage());
}
}
if (con != null && !conn.isClosed()) {
try {
con.close();
} catch (Exception e2) {
log.warn("Cannot close connection: " + e2.getMessage());
}
}
}
In theory it is not 100% perfect because between the the checking the close state and the close itself there is a little room for the change for state. In the worst case you will get a warning in long. - but it is lesser than the possibility of state change in long run queries. We are using this pattern in production with an "avarage" load (150 simultanous user) and we had no problem with it - so never see that warning message.
Some convenience functions:
public static void silentCloseResultSets(Statement st) {
try {
while (!(!st.getMoreResults() && (st.getUpdateCount() == -1))) {}
} catch (SQLException ignore) {}
}
public static void silentCloseResultSets(Statement ...statements) {
for (Statement st: statements) silentCloseResultSets(st);
}
As far as I remember, in the current JDBC, Resultsets and statements implement the AutoCloseable interface. That means they are closed automatically upon being destroyed or going out of scope.

maximum open cursors exceeded exception in java code

this my code to execute update query
public boolean executeQuery(Connection con,String query) throws SQLException
{
boolean flag=false;
try
{
Statement st = con.createStatement();
flag=st.execute(query);
st.close();
st=null;
flag=true;
}
catch (Exception e)
{
flag=false;
e.printStackTrace();
throw new SQLException(" UNABLE TO FETCH INSERT");
}
return flag;
}
maximum open cursor is set to 4000
code is executing
update tableA set colA ='x',lst_upd_date = trunc(sysdate) where trunc(date) = to_date('"+date+"','dd-mm-yyyy')
update query for around 8000 times
but after around 2000 days its throwing exception as "maximum open cursors exceeded"
please suggest code changes for this.
#TimBiegeleisen here is the code get connecttion
public Connection getConnection(String sessId)
{
Connection connection=null;
setLastAccessed(System.currentTimeMillis());
connection=(Connection)sessionCon.get(sessId);
try
{
if(connection==null || connection.isClosed() )
{
if ( ds == null )
{
InitialContext ic = new InitialContext();
ds = (DataSource) ic.lookup("java:comp/env/iislDB");
}
connection=ds.getConnection();
sessionCon.put(sessId, connection);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return connection;
}
`
error stack is as bellow
java.sql.SQLException: ORA-01000: maximum open cursors exceeded
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208)
at oracle.jdbc.ttc7.Oopen.receive(Oopen.java:118)
at oracle.jdbc.ttc7.TTC7Protocol.open(TTC7Protocol.java:472)
at oracle.jdbc.driver.OracleStatement.<init>(OracleStatement.java:499)
at oracle.jdbc.driver.OracleConnection.privateCreateStatement(OracleConnection.java:683)
at oracle.jdbc.driver.OracleConnection.createStatement(OracleConnection.java:560)
at org.apache.tomcat.dbcp.dbcp.DelegatingConnection.createStatement(DelegatingConnection.java:257)
at org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.createStatement(PoolingDataSource.java:216)
at com.iisl.business.adminbo.computeindex.MoviIndexComputeBO.calculateMoviValue(MoviIndexComputeBO.java:230)
Your code has a cursor leak. That's what is causing the error. It seems unlikely that your code can really go 2000 days (about 5.5 years) before encountering the error. If that was the case, I'd wager that you'd be more than happy to restart a server twice a decade.
In your try block, you create a Statement. If an exception is thrown between the time that the statement is created and the time that st.close() is called, your code will leave the statement open and you will have leaked a cursor. Once a session has leaked 4000 cursors, you'll get the error. Increasing max_open_cursors will merely delay when the error occurs, it won't fix the underlying problem.
The underlying problem is that your try/ catch block needs a finally that closes the Statement if it was left open by the try. For this to work, you'd need to declare st outside of the try
finally {
if (st != null) {
st.close();
}
}
As mentioned in another response you will leak cursors if an exception is thrown during the statement execution because st.close() won't be executed. You can use Java's try-with-resources syntax to be sure that your statement object is closed:
try (Statement st = con.createStatement())
{
flag=st.execute(query);
flag=true;
}
catch (Exception e)
{
flag=false;
e.printStackTrace();
throw new SQLException(" UNABLE TO FETCH INSERT");
}
return flag;
One of quickest solution is to increase cursor that each connection can handle by issuing following command on SQL prompt:
alter system set open_cursors = 1000
Also, add finally block in your code and close the connection to help closing cursors when ever exception occurs.
Also, run this query to see where actually cursor are opened.
select sid ,sql_text, count(*) as "OPEN CURSORS", USER_NAME from v$open_cursor
finally {
if (connection!=null) {
connection.close();
}

automatic closing of result-set in Java SQL

Consider the following code
ResultSet rs = null;
Statement st = null;
try {
//do somehting
} catch (Exception e){
//do something
} finally {
if(st != null){
try {
st.close();
} catch (SQLException e) {
log.error("Exception while closing statement: " + e);
}
}
}
The question is that when we close the statement, will it close the result set as well or do we need to explicitly close the result set like this
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
log.error("Exception while closing result set: " + e);
}
}
I thought that closing the statement will automatically close the result set, but FindBugs throws the following warning if I don't explicitly close the result set
This method may fail to clean up java.sql.ResultSet
When a Statement object is closed, its current ResultSet object, if one exists, is also closed.
This and this shows that Oracle may have problems and you might have to explicitly close the ResultSet. But again, as per the Javadocs, this shouldn't be an issue. Hence, the warning,maybe.
You can't count on the ResultSet being closed automatically, it depends on the driver implementation and how compliant it is. The best policy is to close the ResultSet explicitly.
When you close the statement or connection, all it's children should be closed too by default.

Reusing a PreparedStatement

I ran findbugs on our code base and it pointed out there are two more Statements that still need to be closed. In this section of the code we run:
preparedStatement = connection.prepareStatement(query);
for 3 different queries, reusing preparedStatement. In the finally block we do close the resource:
finally{
try{
if (resultSet != null)
resultSet.close();
} catch (Exception e) {
exceptionHandler.ignore(e);
}
try {
if (preparedStatement != null)
preparedStatement.close();
} catch(Exception e) {
exceptionHandler.ignore(e);
}
Should the statement be closed before the next connection.prepareStatement(query); or is this findbugs being cautious?
Yes, the statement must be closed before you perform the next connection.prepareStatement. Otherwise, you're losing your reference to the un-closed previous one (aka leaking statements). Wrap a try {} finally {} around each statement use, closing it in the finally.

Categories

Resources