How to prevent from transaction to close at the catch(Exception e)? - java

I'm trying to run a query from java to PosgresSQL and I get an error from the stmt.execute(sql)
I would like to execute a new query to help me print out the specific row failing, but when I get to the catch (Exception e) the transaction is aborted.
I cant create a new transaction because I'm working with temp tables. How do I prevent the transaction to abort?
org.postgresql.util.PSQLException: ERROR: current transaction is aborted, commands ignored until end of transaction block
try (Statement stmt = data.db.getConnection().createStatement()) {
// data.db.getConnection().setSavepoint("sp01");
// insert to fact table
TableSchema factTableSchema = factInfo.getTableSchema();
// build SQL
String sql = "Select * From....";
try {
stmt.execute(sql); // this row is failing
}
catch (Exception e) {
try {
// now i would like to run a query only in case arrived here, but the transaction is closed
// how could i prevent from trasanction to close ?
ResultSet rs = stmt.executeQuery(" SELECT Bla,Bla From..");
Log.debug("");
}
catch (Exception e2) {
Log.debug("");
}
}

Create a new statement in the 2nd try block before you execute the query.
Statement stmt = data.db.getConnection().createStatement();
ResultSet rs = stmt.executeQuery(" SELECT Bla,Bla From..");
ResultSet needs to be connected and alive to perform a next();

Related

Impala invalidate metadata through jdbc

Is there any way to invalidate metadata on Impala through jdbc?
I've tried the following (I am using Cloudera_ImpalaJDBC4_2.5.5.1007 driver):
// invalidate metadata and rebuild index on Impala
try {
Statement stmt = impalaConn.createStatement();
try {
String query = "INVALIDATE METADATA;";
ResultSet resultSet = stmt.executeQuery(query);
while (resultSet.next()) {
// do something
}
}
finally {
stmt.close();
}
}
catch(SQLException ex) {
while (ex != null)
{
ex.printStackTrace();
ex = ex.getNextException();
}
System.exit(1);
}
but I got the following exception:
java.sql.SQLDataException: [Simba][JDBC](11300) A ResultSet was expected but not generated from query "INVALIDATE METADATA;". Query not executed.
at com.cloudera.impala.exceptions.ExceptionConverter.toSQLException(ExceptionConverter.java:136)
at com.cloudera.impala.jdbc.common.SStatement.checkCondition(SStatement.java:2274)
at com.cloudera.impala.jdbc.common.SStatement.executeNoParams(SStatement.java:2704)
at com.cloudera.impala.jdbc.common.SStatement.executeQuery(SStatement.java:880)
at ico.az.deploy.TestSuite.testTeradata(TestSuite.java:103)
at ico.az.deploy.TestSuite.run(TestSuite.java:310)
at ico.az.deploy.TestSuite.main(TestSuite.java:345)
Any idea?
Yes. That query doesn't return a ResultSet. Use Statement.executeUpdate(String) instead. As the JavaDoc notes, bold added for emphasis, Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing.
stmt.executeUpdate(query);

Statement.setQueryTimeout does not throw an Exception (SQL SERVER)

I'm using JDBC Microsoft SQL SERVER DRIVER and when i set query timeout, the driver return the query results until that moment.
But the driver does not throw a SQLTimeoutException (see javadoc: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#setQueryTimeout(int))
How can i solve this problem? I need to know when occurs a timeout...
Sample code, where we can see the problem:
try {
Connection con = ConnectionFactory.getNewConnection();
Statement st = con.createStatement();
st.setQueryTimeout(10);
ResultSet rs = st.executeQuery(" ... some query takes long time ... ");
while (rs.next()) {
// ...
// actions with result
// ...
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
I believe the query returns a partial result. Because is possible to scroll through the resultset and print the result ...

How to run SQL TRANSACTION in a PreparedStatement

I have a SQL Transaction query that I am unable to run. Can any one tell me please why? I have failed to run it using preparedstament.executequery(); as well.
START TRANSACTION;
SELECT total_installment_remaining FROM payment_loan WHERE loan_id = 1 FOR UPDATE;
UPDATE payment_loan SET total_installment_remaining =total_installment_remaining-1 WHERE loan_id = 1;
COMMIT;
Turn off autocommit, then use Connection.commit() to end the transaction.
connection.setAutocommit(false);
Statement stmt = con2.createStatement();
// this will automatically start a transaction
ResultSet rs = stmt.executeQuery("SELECT total_installment_remaining FROM payment_loan WHERE loan_id = 1 FOR UPDATE");
// process the result if needed
...
stmt.executeUpdate("UPDATE payment_loan SET total_installment_remaining =total_installment_remaining-1 WHERE loan_id = 1");
// end the transaction and persist then changes
connection.commit();
If you don't need the result of the SELECT in your code, then you don't really need the SELECT ... FOR UPDATE in the first place, because the UPDATE will lock the row anyway.
String query = "START TRANSACTION;SELECT total_installment_remaining FROMpayment_loan WHERE loan_id = 1 FOR UPDATE;UPDATE payment_loan SET total_installment_remaining =total_installment_remaining-1 WHERE loan_id = 1;COMMIT;";
try {
ps2 = con2.prepareStatement(query);
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
rs2.getInt(1);
}
// rs.close();
// con.close();
} catch (SQLException e) {
logger.error("",e);
// TODO Auto-generated catch block
e.printStackTrace();
}

Updating existing Row on database jdbc

No error is showing when i click the button but the table on the database doesn't update.
String heh = jLabel17.getText();
try {
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch (SQLException err) {
System.out.println(err.getMessage() );
}
You have messed up the query totally,
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
should be,
stmt.executeUpdate("UPDATE books SET availability='Unavailable' where Book_title='"+heh+"' ");
It is advisable to print query before you execute , as that avoids common mistakes. Also try to use Prepared Statements as yours is vulnerable to sql injection
Read this Prepared Statements and JDBC Drivers
AFTER HOURS OF RESEARCH, I FOUND THE SOLUTION, I REPLACED THIS
String heh = jLabel17.getText();
try{
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch(SQLException err){
System.out.println(err);
}
WITH THIS CODE
String heh = jLabel17.getText();
try{
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Dafuq7","Dafuq7","Dafuq7");
// Creating Statement for query execution
stmt = con.createStatement();
// creating Query String
String query = "UPDATE books SET availability='NOT AVAILABLE' WHERE book_title='"+heh+"'";
// Updating Table
int rows = stmt.executeUpdate(query);
System.out.println(rows + " Rows Updated Successfully....");
} catch (Exception e) {
System.out.println(e.toString());
}

How can I avoid ResultSet is closed exception in Java?

As soon as my code gets to my while(rs.next()) loop it produces the ResultSet is closed exception. What causes this exception and how can I correct for it?
EDIT: I notice in my code that I am nesting while(rs.next()) loop with another (rs2.next()), both result sets coming from the same DB, is this an issue?
Sounds like you executed another statement in the same connection before traversing the result set from the first statement. If you're nesting the processing of two result sets from the same database, you're doing something wrong. The combination of those sets should be done on the database side.
This could be caused by a number of reasons, including the driver you are using.
a) Some drivers do not allow nested statements. Depending if your driver supports JDBC 3.0 you should check the third parameter when creating the Statement object. For instance, I had the same problem with the JayBird driver to Firebird, but the code worked fine with the postgres driver. Then I added the third parameter to the createStatement method call and set it to ResultSet.HOLD_CURSORS_OVER_COMMIT, and the code started working fine for Firebird too.
static void testNestedRS() throws SQLException {
Connection con =null;
try {
// GET A CONNECTION
con = ConexionDesdeArchivo.obtenerConexion("examen-dest");
String sql1 = "select * from reportes_clasificacion";
Statement st1 = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
ResultSet rs1 = null;
try {
// EXECUTE THE FIRST QRY
rs1 = st1.executeQuery(sql1);
while (rs1.next()) {
// THIS LINE WILL BE PRINTED JUST ONCE ON
// SOME DRIVERS UNLESS YOU CREATE THE STATEMENT
// WITH 3 PARAMETERS USING
// ResultSet.HOLD_CURSORS_OVER_COMMIT
System.out.println("ST1 Row #: " + rs1.getRow());
String sql2 = "select * from reportes";
Statement st2 = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
// EXECUTE THE SECOND QRY. THIS CLOSES THE FIRST
// ResultSet ON SOME DRIVERS WITHOUT USING
// ResultSet.HOLD_CURSORS_OVER_COMMIT
st2.executeQuery(sql2);
st2.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs1.close();
st1.close();
}
} catch (SQLException e) {
} finally {
con.close();
}
}
b) There could be a bug in your code. Remember that you cannot reuse the Statement object, once you re-execute a query on the same statement object, all the opened resultsets associated with the statement are closed. Make sure you are not closing the statement.
Also, you can only have one result set open from each statement. So if you are iterating through two result sets at the same time, make sure they are executed on different statements. Opening a second result set on one statement will implicitly close the first.
http://java.sun.com/javase/6/docs/api/java/sql/Statement.html
The exception states that your result is closed. You should examine your code and look for all location where you issue a ResultSet.close() call. Also look for Statement.close() and Connection.close(). For sure, one of them gets called before rs.next() is called.
You may have closed either the Connection or Statement that made the ResultSet, which would lead to the ResultSet being closed as well.
Proper jdbc call should look something like:
try {
Connection conn;
Statement stmt;
ResultSet rs;
try {
conn = DriverManager.getConnection(myUrl,"","");
stmt = conn.createStatement();
rs = stmt.executeQuery(myQuery);
while ( rs.next() ) {
// process results
}
} catch (SqlException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
} finally {
// you should release your resources here
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
} catch (SqlException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
you can close connection (or statement) only after you get result from result set. Safest way is to do it in finally block. However close() could also throe SqlException, hence the other try-catch block.
I got same error everything was correct only i was using same statement interface object to execute and update the database.
After separating i.e. using different objects of statement interface for updating and executing query i resolved this error. i.e. do get rid from this do not use same statement object for both updating and executing the query.
Check whether you have declared the method where this code is executing as static. If it is static there may be some other thread resetting the ResultSet.
make sure you have closed all your statments and resultsets before running rs.next. Finaly guarantees this
public boolean flowExists( Integer idStatusPrevious, Integer idStatus, Connection connection ) {
LogUtil.logRequestMethod();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement( Constants.SCRIPT_SELECT_FIND_FLOW_STATUS_BY_STATUS );
ps.setInt( 1, idStatusPrevious );
ps.setInt( 2, idStatus );
rs = ps.executeQuery();
Long count = 0L;
if ( rs != null ) {
while ( rs.next() ) {
count = rs.getLong( 1 );
break;
}
}
LogUtil.logSuccessMethod();
return count > 0L;
} catch ( Exception e ) {
String errorMsg = String
.format( Constants.ERROR_FINALIZED_METHOD, ( e.getMessage() != null ? e.getMessage() : "" ) );
LogUtil.logError( errorMsg, e );
throw new FatalException( errorMsg );
} finally {
rs.close();
ps.close();
}
A ResultSetClosedException could be thrown for two reasons.
1.) You have opened another connection to the database without closing all other connections.
2.) Your ResultSet may be returning no values. So when you try to access data from the ResultSet java will throw a ResultSetClosedException.
It happens also when using a ResultSet without being in a #Transactional method.
ScrollableResults results = getScrollableResults("select e from MyEntity e");
while (results.next()) {
...
}
results.close();
if MyEntity has eager relationships with other entities. the second time results.next() is invoked the ResultSet is closed exception is raised.
so if you use ScrollableResults on entities with eager relationships make sure your method is run transactionally.
"result set is closed" happened to me when using tag <collection> in MyBatis nested (one-to-many) xml <select> statement
A Spring solution could be to have a (Java) Spring #Service layer, where class/methods calling MyBatis select-collection statements are annotated with
#Transactional(propagation = Propagation.REQUIRED)
annotations being:
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
this solution does not require to set the following datasource properties (i.e., in JBoss EAP standalone*.xml):
<xa-datasource-property name="downgradeHoldCursorsUnderXa">**true**\</xa-datasource-property>
<xa-datasource-property name="resultSetHoldability">**1**</xa-datasource-property>

Categories