List of usage examples for java.sql Statement isClosed
boolean isClosed() throws SQLException;
Statement
object has been closed. From source file:com.generalbioinformatics.rdf.VirtuosoConnection.java
@Override public void sparqlConstruct(String query, OutputStream os) throws StreamException { Connection con = null;/* w w w.ja v a 2 s . c o m*/ Statement st = null; RecordStream rs = null; try { con = getConnection(); st = con.createStatement(); //TODO: evaluate logEnable(st, true, false); rs = new ResultSetRecordStream(executeQuery(st, "SPARQL " + prefixes + " " + query), st, isManagedConnection() ? con : null); NtWriter nt = new NtWriter(os); Record r; while ((r = rs.getNext()) != null) { String s = "" + r.get("S"); String p = "" + r.get("P"); String o = "" + r.get("O"); nt.writeStatement(s, p, o); } } catch (SQLException ex) { throw new StreamException(ex); } catch (IOException ex) { throw new StreamException(ex); } finally { try { if (rs != null) rs.close(); if (st != null && !st.isClosed()) st.close(); if (isManagedConnection() && !con.isClosed()) con.close(); } catch (SQLException ex) { /* ignore */ } } }
From source file:com.ipcglobal.fredimportaws.TsvsToRedshift.java
/** * Copy s3 files to redshift table.// w w w . j a va 2 s . co m * * @throws Exception the exception */ private void copyS3FilesToRedshiftTable() throws Exception { GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest(); GetSessionTokenResult getSessionTokenResult = stsClient.getSessionToken(getSessionTokenRequest); Credentials credentialsToken = getSessionTokenResult.getCredentials(); String jdbcRedshiftUrl = properties.getProperty("jdbcRedshiftUrl"); String jdbcRedshiftDriverClass = properties.getProperty("jdbcRedshiftDriverClass"); String jdbcRedshiftLogin = properties.getProperty("jdbcRedshiftLogin"); String jdbcRedshiftPassword = properties.getProperty("jdbcRedshiftPassword"); Class.forName(jdbcRedshiftDriverClass); Connection con = null; Statement statement = null; try { String tableName = properties.getProperty("tableNameFred").trim(); con = DriverManager.getConnection(jdbcRedshiftUrl, jdbcRedshiftLogin, jdbcRedshiftPassword); statement = con.createStatement(); createDatabase(statement); // just in case... // Drop/Create table (more efficient than deleting all of the rows) dropTable(statement, tableName); statement.execute(createTableStatement(tableName)); long beforeCopy = System.currentTimeMillis(); String s3SourceBucketPrefix = "s3://" + awsBucketName + "/" + awsBucketTsvPrefix + "/"; String s3Copy = "copy " + tableName + " from '" + s3SourceBucketPrefix + "' " + "CREDENTIALS 'aws_access_key_id=" + credentialsToken.getAccessKeyId().replace("\\", "\\\\") + ";" + "aws_secret_access_key=" + credentialsToken.getSecretAccessKey().replace("\\", "\\\\") + ";" + "token=" + credentialsToken.getSessionToken().replace("\\", "\\\\") + "' " + "delimiter '\\t' gzip"; statement.executeUpdate(s3Copy); } catch (Exception e) { log.error(e); throw e; } finally { try { if (statement != null && !statement.isClosed()) statement.close(); } catch (Exception e) { log.warn("Exception closing statement: " + e.getMessage()); } try { if (con != null && !con.isClosed()) con.close(); } catch (Exception e) { log.warn("Exception closing connection: " + e.getMessage()); } } }
From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java
private void doTestSelectAll(String tableName, int maxRows, int fetchSize) throws Exception { boolean isPartitionTable = tableName.equals(partitionedTableName); Statement stmt = con.createStatement(); if (maxRows >= 0) { stmt.setMaxRows(maxRows);/*from w w w . j a v a2s.co m*/ } if (fetchSize > 0) { stmt.setFetchSize(fetchSize); assertEquals(fetchSize, stmt.getFetchSize()); } // JDBC says that 0 means return all, which is the default int expectedMaxRows = maxRows < 1 ? 0 : maxRows; assertNotNull("Statement is null", stmt); assertEquals("Statement max rows not as expected", expectedMaxRows, stmt.getMaxRows()); assertFalse("Statement should not be closed", stmt.isClosed()); ResultSet res; // run some queries res = stmt.executeQuery("select * from " + tableName); assertNotNull("ResultSet is null", res); assertTrue("getResultSet() not returning expected ResultSet", res == stmt.getResultSet()); assertEquals("get update count not as expected", 0, stmt.getUpdateCount()); int i = 0; ResultSetMetaData meta = res.getMetaData(); int expectedColCount = isPartitionTable ? 3 : 2; assertEquals("Unexpected column count", expectedColCount, meta.getColumnCount()); String colQualifier = ((tableName != null) && !tableName.isEmpty()) ? tableName.toLowerCase() + "." : ""; boolean moreRow = res.next(); while (moreRow) { try { i++; assertEquals(res.getInt(1), res.getInt(colQualifier + "under_col")); assertEquals(res.getString(1), res.getString(colQualifier + "under_col")); assertEquals(res.getString(2), res.getString(colQualifier + "value")); if (isPartitionTable) { assertEquals(res.getString(3), partitionedColumnValue); assertEquals(res.getString(3), res.getString(colQualifier + partitionedColumnName)); } assertFalse("Last result value was not null", res.wasNull()); assertNull("No warnings should be found on ResultSet", res.getWarnings()); res.clearWarnings(); // verifying that method is supported // System.out.println(res.getString(1) + " " + res.getString(2)); assertEquals("getInt and getString don't align for the same result value", String.valueOf(res.getInt(1)), res.getString(1)); assertEquals("Unexpected result found", "val_" + res.getString(1), res.getString(2)); moreRow = res.next(); } catch (SQLException e) { System.out.println(e.toString()); e.printStackTrace(); throw new Exception(e.toString()); } } // supposed to get 500 rows if maxRows isn't set int expectedRowCount = maxRows > 0 ? maxRows : 500; assertEquals("Incorrect number of rows returned", expectedRowCount, i); // should have no more rows assertEquals(false, moreRow); assertNull("No warnings should be found on statement", stmt.getWarnings()); stmt.clearWarnings(); // verifying that method is supported assertNull("No warnings should be found on connection", con.getWarnings()); con.clearWarnings(); // verifying that method is supported stmt.close(); assertTrue("Statement should be closed", stmt.isClosed()); }
From source file:fetchBooks.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w w w . ja v a2 s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); try { System.out.println("Inside try 1"); Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance(); //setting up the connection String dbURL = "jdbc:derby://localhost:1527/autolib_db_test"; Connection conn = DriverManager.getConnection(dbURL, "ishtiaq", "ishtiaq"); Statement stmt = null; ResultSet rslt = null; if (conn == null) { System.out.println("Connection Failed"); } stmt = conn.createStatement(); String searchTopic = request.getParameter("topic"); //running a select query in the underlying database on table named books_tbl. System.out.println("SEARCH TOPIC " + searchTopic); String sqlQry = "SELECT * FROM books_tbl where topic = '" + searchTopic.toUpperCase() + "'"; rslt = stmt.executeQuery(sqlQry); //query is executed by the statement. JSONObject jObj = new JSONObject(); //new jsonobject is created JSONArray bookArr = new JSONArray(); //new json array is created JSONObject book; try { System.out.println("Inside Try"); while (rslt.next()) { book = new JSONObject(); book.put("id", rslt.getInt("id")); //put the id of the book converted into Integer in "id" book.put("name", rslt.getString("bookname")); //put the bookname into "name" bookArr.put(book); //bookArr[] is inserted with book ID and bookname which are mandatory fields. } jObj.put("Books", bookArr); //maps bookArr content to String name "Books" } catch (JSONException jse) { } response.setContentType("application/json"); response.getWriter().write(jObj.toString()); //toString confirms to JSON syntax rules and converts the jObj content to json text. //System.out.println("after json"); if (!stmt.isClosed()) stmt.close(); //closing connection if (!rslt.isClosed()) rslt.close(); } catch (Exception e) { //return null; } }
From source file:org.apache.hive.jdbc.TestJdbcDriver2.java
@Test public void testCloseResultSet() throws Exception { Statement stmt = con.createStatement(); // execute query, ignore exception if any ResultSet res = stmt.executeQuery("select * from " + tableName); // close ResultSet, ignore exception if any res.close();/*from w w w . j a v a 2 s . c om*/ // A statement should be open even after ResultSet#close assertFalse(stmt.isClosed()); // A Statement#cancel after ResultSet#close should be a no-op try { stmt.cancel(); } catch (SQLException e) { failWithExceptionMsg(e); } stmt.close(); stmt = con.createStatement(); // execute query, ignore exception if any res = stmt.executeQuery("select * from " + tableName); // close ResultSet, ignore exception if any res.close(); // A Statement#execute after ResultSet#close should be fine too try { stmt.executeQuery("select * from " + tableName); } catch (SQLException e) { failWithExceptionMsg(e); } // A Statement#close after ResultSet#close should close the statement stmt.close(); assertTrue(stmt.isClosed()); }
From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java
private List<AbstractEntity> read(final String query, final Class<?> type, final int limit, final Connection conn) throws Exception { // Make sure the type for the class is available. StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(type); boolean joinedList = AbstractJoinGraph.hasJoinedList(enref); SQLQuery parser = new SQLQuery(type); String selectsql = parser.parse(query, limit); Statement stmnt = conn.createStatement(); List<AbstractEntity> entities = new ArrayList<AbstractEntity>(); HashMap<String, AbstractEntity> refindx = null; try {/*from w w w . j ava2 s . c om*/ log.debug("SELECT SQL [" + selectsql + "]"); ResultSet rs = stmnt.executeQuery(selectsql); try { if (joinedList) { refindx = new HashMap<String, AbstractEntity>(); } while (rs.next()) { if (!joinedList) { AbstractJoinGraph gr = AbstractJoinGraph.lookup(type); Object obj = type.newInstance(); if (!(obj instanceof AbstractEntity)) throw new Exception("Unsupported Entity type [" + type.getCanonicalName() + "]"); AbstractEntity entity = (AbstractEntity) obj; Stack<KeyValuePair<Class<?>>> path = new Stack<KeyValuePair<Class<?>>>(); KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>(); cls.setValue(entity.getClass()); path.push(cls); EntityHelper.setEntity(entity, rs, gr, path); entities.add(entity); } else { EntityHelper.setEntity(enref, refindx, rs); } } } finally { if (rs != null && !rs.isClosed()) { rs.close(); } } if (joinedList) { for (String key : refindx.keySet()) { entities.add(refindx.get(key)); } } return entities; } finally { if (stmnt != null && !stmnt.isClosed()) { stmnt.close(); } } }
From source file:fetchBookDetails.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w . j a v a 2 s. c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); try { System.out.println("Inside try 1"); Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance(); //setting up connection String dbURL = "jdbc:derby://localhost:1527/autolib_db_test"; Connection conn = DriverManager.getConnection(dbURL, "ishtiaq", "ishtiaq"); Statement stmt = null; ResultSet rslt = null; if (conn == null) { System.out.println("Connection Failed"); } stmt = conn.createStatement(); String bookId = request.getParameter("book"); // pass this book value from displayBookDetails function String buyBook = request.getParameter("buy"); // pass this book value from displayBookDetails function String sqlQry = ""; if (buyBook.equals("YES")) { //if a book is selected to be bought Integer bookQty = Integer.parseInt(request.getParameter("qty")); // pass this book value from displayBookDetails function sqlQry = "update books_tbl set qty = qty - " + bookQty.toString() + " where id = " + bookId + ""; //reducing quantity by bookQty which increments by 1 on every click stmt.execute(sqlQry); //executing the update query } System.out.println("SEARCH Book id " + bookId); //query to return book details by giving the ID value sqlQry = "SELECT * FROM books_tbl where id = " + bookId + ""; rslt = stmt.executeQuery(sqlQry); //creating JSON object, array object and a jason variable JSONObject jObj = new JSONObject(); JSONArray bookArr = new JSONArray(); JSONObject bookData; try { System.out.println("Inside Try"); //adding ID, name, author, price, topic, available and qty to bookData by using put while (rslt.next()) { bookData = new JSONObject(); bookData.put("id", rslt.getInt("id")); bookData.put("name", rslt.getString("bookname")); bookData.put("author", rslt.getString("author")); bookData.put("price", rslt.getInt("price")); bookData.put("topic", rslt.getString("topic")); bookData.put("available", rslt.getBoolean("available")); bookData.put("qty", rslt.getInt("qty")); bookArr.put(bookData); //putting all bookdata in book array } jObj.put("Books", bookArr); //adding book array content to string named "Books" } catch (JSONException jse) { } response.setContentType("application/json"); response.getWriter().write(jObj.toString()); //closing connection if (!stmt.isClosed()) stmt.close(); if (!rslt.isClosed()) rslt.close(); } catch (Exception e) { //return null; } }
From source file:org.apache.hive.jdbc.TestJdbcDriver2.java
private void doTestSelectAll(String tableName, int maxRows, int fetchSize) throws Exception { boolean isPartitionTable = tableName.equals(partitionedTableName); Statement stmt = con.createStatement(); if (maxRows >= 0) { stmt.setMaxRows(maxRows);/*w w w . ja v a2s . c o m*/ } if (fetchSize > 0) { stmt.setFetchSize(fetchSize); assertEquals(fetchSize, stmt.getFetchSize()); } // JDBC says that 0 means return all, which is the default int expectedMaxRows = maxRows < 1 ? 0 : maxRows; assertNotNull("Statement is null", stmt); assertEquals("Statement max rows not as expected", expectedMaxRows, stmt.getMaxRows()); assertFalse("Statement should not be closed", stmt.isClosed()); ResultSet res; // run some queries res = stmt.executeQuery("select * from " + tableName); assertNotNull("ResultSet is null", res); assertTrue("getResultSet() not returning expected ResultSet", res == stmt.getResultSet()); assertEquals("get update count not as expected", -1, stmt.getUpdateCount()); int i = 0; ResultSetMetaData meta = res.getMetaData(); int expectedColCount = isPartitionTable ? 3 : 2; assertEquals("Unexpected column count", expectedColCount, meta.getColumnCount()); boolean moreRow = res.next(); while (moreRow) { try { i++; assertEquals(res.getInt(1), res.getInt(tableName + ".under_col")); assertEquals(res.getInt(1), res.getInt("under_col")); assertEquals(res.getString(1), res.getString(tableName + ".under_col")); assertEquals(res.getString(1), res.getString("under_col")); assertEquals(res.getString(2), res.getString(tableName + ".value")); assertEquals(res.getString(2), res.getString("value")); if (isPartitionTable) { assertEquals(res.getString(3), partitionedColumnValue); assertEquals(res.getString(3), res.getString(partitionedColumnName)); assertEquals(res.getString(3), res.getString(tableName + "." + partitionedColumnName)); } assertFalse("Last result value was not null", res.wasNull()); assertNull("No warnings should be found on ResultSet", res.getWarnings()); res.clearWarnings(); // verifying that method is supported // System.out.println(res.getString(1) + " " + res.getString(2)); assertEquals("getInt and getString don't align for the same result value", String.valueOf(res.getInt(1)), res.getString(1)); assertEquals("Unexpected result found", "val_" + res.getString(1), res.getString(2)); moreRow = res.next(); } catch (SQLException e) { System.out.println(e.toString()); e.printStackTrace(); throw new Exception(e.toString()); } } // supposed to get 500 rows if maxRows isn't set int expectedRowCount = maxRows > 0 ? maxRows : 500; assertEquals("Incorrect number of rows returned", expectedRowCount, i); // should have no more rows assertEquals(false, moreRow); assertNull("No warnings should be found on statement", stmt.getWarnings()); stmt.clearWarnings(); // verifying that method is supported assertNull("No warnings should be found on connection", con.getWarnings()); con.clearWarnings(); // verifying that method is supported stmt.close(); assertTrue("Statement should be closed", stmt.isClosed()); }
From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java
/** * Close statement instance.//from w w w .j av a 2 s. c o m * @param stmt statement instance. */ protected static void closeStmt(Statement stmt) { try { if (stmt != null && !stmt.isClosed()) stmt.close(); } catch (SQLException e) { LOG.warn("Failed to close statement " + getMessage(e)); } }
From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java
@Test public void testExecuteSQLQuery() throws Exception { Statement statement = getConnection().createStatement(); ResultSet rs = statement.executeQuery(SQL_EMPS); assertSame(statement, rs.getStatement()); assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType()); assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency()); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability()); assertFalse(rs.isClosed());// ww w . j a va 2 s . co m assertTrue(rs.isBeforeFirst()); assertFalse(rs.isAfterLast()); assertEquals(1, rs.findColumn("empno")); assertEquals(2, rs.findColumn("ename")); assertEquals(3, rs.findColumn("salary")); assertEquals(4, rs.findColumn("hiredate")); int count = printResultSet(rs); assertEquals(getEmpRowCount(), count); assertFalse(rs.isBeforeFirst()); assertTrue(rs.isAfterLast()); rs.close(); assertTrue(rs.isClosed()); statement.close(); assertTrue(statement.isClosed()); }