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);
Related
I tried to get specific value where the column of names in my database contains "jansen",but when i run my code it shows error like this
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'jansen' in 'where clause'
here is my code
try {
Statement stmt=MyConnection.getConnection().createStatement();
ResultSet rs=stmt.executeQuery("select * from emp where name = jansen");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}catch (Exception e){
System.out.println(e);
}
[and here is my database in Sqlyog]
You should put quotes around string values in your SQL statement.
"select * from emp where name = 'jansen'"
Another issue you may run into later, is that your resources (e.g. connection, statement, ...) aren't cleaned up after you've used them. You should actually call the close() function after using it. You would then have to put that code inside a finally block, and again catch it to prevent having the close function itself throwing exceptions. Because it would be messy and bloated, there's a better solution to clean things up:
Create your statement between the braces of your try, and it will close it cleanly for you. (It's called a try-with-resources statement)
try (Statement stmt = MyConnection.getConnection().createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
...
}
} catch (SQLException e) {
System.out.println(e);
}
You can read more about executing SQL statements in java, in the official tutorial.
You should use a PreparedStatement instead of Statement in this way:
PreparedStatement statement = MyConnection.getConnection().prepareStatement("select * from emp where name = :empId");
statement.setString(empId, "jansen");
ResultSet rs = statement.executeQuery();
Then "jansen" would be replaced by String variable with dynamic name.
I tried to make crud , but insert statement do not work from code
try {
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
conn2 = DriverManager.getConnection(dbURL2, username, password);
String sql="INSERT INTO Produce(name,description,Produce_Date,Price,CATEGORY_ID,Person_ID)VALUES('"+name+"','"+description+"',TO_DATE('"+sqlDate+"', 'yyyy-mm-dd'),"+price+","+category_Id+","+person_id+")";
System.out.println(sql);
stmt = conn2.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
if (conn2 != null && !conn2.isClosed()) {
conn2.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
I made a System.out.println to see my sql and to execute it to understand where is the problem, this is my String, and it works in sqlDeveloper:
INSERT INTO Produce(name,description,Produce_Date,Price,CATEGORY_ID,Person_ID)VALUES('ew','rrr',TO_DATE('2018-11-14', 'yyyy-mm-dd'),12.0,2,2)
you are using insert SQL query to retrieve result.
I believe to retrieve name you need to execute select statement
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();
I am practicing JDBC batch processing and having errors:
error 1: Unsupported feature
error 2: Execute cannot be empty or null
Property files include:
itemsdao.updateBookName = Update Books set bookname = ? where books.id = ?
itemsdao.updateAuthorName = Update books set authorname = ? where books.id = ?
I know I can execute about DML statements in one update, but I am practicing batch processing in JDBC.
Below is my method
public void update(Item item) {
String query = null;
try {
connection = DbConnector.getConnection();
property = SqlPropertiesLoader.getProperties("dml.properties");
connection.setAutoCommit(false);
if ( property == null )
{
Logging.log.debug("dml.properties does not exist. Check property loader or file name is spelled right");
return;
}
query = property.getProperty("itemsdao.updateBookName");
statement = connection.prepareStatement(query);
statement.setString(1, item.getBookName());
statement.setInt(2, item.getId());
statement.addBatch(query);
query = property.getProperty("itemsdao.updateAuthorName");
statement = connection.prepareStatement(query);
statement.setString(1, item.getAuthorName());
statement.setInt(2, item.getId());
statement.addBatch(query);
statement.executeBatch();
connection.commit();
}catch (ClassNotFoundException e) {
Logging.log.error("Connection class does not exist", e);
}
catch (SQLException e) {
Logging.log.error("Violating PK constraint",e);
}
//helper class th
finally {
DbUtil.close(connection);
DbUtil.closePreparedStatement(statement);
}
You are mixing together methods of Statement and PreparedStatement classes:
(addBatch(String sql) belongs to Statement and cannot be called on a PreparedStatement or CallableStatement
addBatch() is to be used with PreparedStatement (as your tutorial shows).
Oracle implements both it's own and standard (JDBC 2.0) batch processing. From the Standard Update Batching docs:
In Oracle JDBC applications, update batching is intended for use with
prepared statements that are being processed repeatedly with different
sets of bind values.
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>