List of usage examples for java.sql PreparedStatement setMaxRows
void setMaxRows(int max) throws SQLException;
ResultSet
object generated by this Statement
object can contain to the given number. From source file:com.quinsoft.zeidon.dbhandler.JdbcHandler.java
/** * Returns a PreparedStatement for the sql. If we are caching PreparedStatements then this will * perform necessary logic for caching. Will bind attributes if there are any. * @param stmt TODO//w ww. j av a2 s . co m * @param sql * @param view TODO * @param entityDef TODO * @param commandType * * @return * @throws SQLException */ private PreparedStatement prepareAndBind(SqlStatement stmt, String sql, View view, EntityDef entityDef, SqlCommand commandType) throws SQLException { PreparedStatement ps = null; // Not every statement can be cached. boolean cacheThisCommand = false; if (commandType != null) { switch (commandType) { case SELECT: case DELETE: cacheThisCommand = true; break; default: break; } } if (cacheThisCommand && cachedStatements != null && entityDef != null) // Are we using cached PreparedStatements? { PreparedStatementCacheKey key = new PreparedStatementCacheKey(entityDef, commandType, sql); PreparedStatementCacheValue value = cachedStatements.get(key.getKey()); if (value == null) { ps = useDbGenerateKeys() ? transaction.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) : transaction.getConnection().prepareStatement(sql); if (stmt.activateLimit > 0) { task.dblog().debug("setMaxRows = %d", stmt.activateLimit); ps.setMaxRows(stmt.activateLimit); } value = new PreparedStatementCacheValue(ps, sql); cachedStatements.put(key.getKey(), value); } else { task.dblog().trace("Using cached statement for Entity => %s \n=> %s", entityDef, sql); ps = value.ps; } } else { // Some JDBC implementations don't support Statement.NO_GENERATED_KEYS (SQLDroid I'm looking // at you) so we have to use the single-argument prepareStatement if we aren't keeping the // generated keys. if (useDbGenerateKeys()) ps = transaction.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); else ps = transaction.getConnection().prepareStatement(sql); if (stmt != null && stmt.activateLimit > 0) { task.dblog().debug("setMaxRows = %d", stmt.activateLimit); ps.setMaxRows(stmt.activateLimit); } } if (stmt != null) // When executing simple statements this will be null. { int idx = 0; for (Object boundValue : stmt.getBoundValues()) { idx++; String valueAsString; if (boundValue instanceof DataField) { DataField dataField = (DataField) boundValue; valueAsString = getTranslator().bindAttributeValue(ps, view, dataField, idx); } else { valueAsString = getTranslator().bindAttributeValue(ps, boundValue, idx); } if (task.dblog().isDebugEnabled()) task.dblog().debug("Bind idx %d = %s (attr value)", idx, leftStr(valueAsString)); } } return ps; }
From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java
public Map find(String type, String query, Map parameters) throws WGQueryException { if (type == null || type.equals("native")) { type = "sql"; }/*from w w w. j a va 2 s . c om*/ List nativeOptions = new ArrayList(); String nativeOptionsString = (String) parameters.get(WGDatabase.QUERYOPTION_NATIVEOPTIONS); if (nativeOptionsString != null) { nativeOptions.addAll(WGUtils.deserializeCollection(nativeOptionsString.toLowerCase(), ",", true)); } ResultSet resultSet = null; String table = null; PreparedStatement stmt; Boolean resetAutocommit = null; Connection connection = null; try { // Create statement connection = getConnection(); boolean isUpdate = nativeOptions.contains("update"); if (isUpdate && !connection.getAutoCommit()) { resetAutocommit = connection.getAutoCommit(); connection.setAutoCommit(true); } if (type.equals("sql")) { stmt = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, (isUpdate ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY)); } else if (type.startsWith("table:")) { table = type.substring(6).trim(); if (!_tables.keySet().contains(table.toLowerCase())) { throw new WGQueryException(query, "Table '" + table + "' does not exist or has no primary key"); } if (query != null && !query.trim().equals("")) { query = "SELECT * FROM " + table + " WHERE " + query; } else { query = "SELECT * FROM " + table; } stmt = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } else { throw new WGQueryException(query, "Unknown query type: " + type); } // Apply parameters if (parameters.containsKey(WGDatabase.QUERYOPTION_MAXRESULTS)) { stmt.setMaxRows(((Number) parameters.get(WGDatabase.QUERYOPTION_MAXRESULTS)).intValue()); } applyQueryParameters(parameters, stmt, query); // Execute and extract data stmt.execute(); resultSet = stmt.getResultSet(); Map results; if (resultSet != null) { results = extractRowResults(resultSet, table); } else { results = new HashMap(); } return results; } catch (SQLException e) { throw new WGQueryException(query, e.getMessage(), e); } finally { if (connection != null && resetAutocommit != null) { try { connection.setAutoCommit(resetAutocommit); } catch (SQLException e) { throw new WGQueryException(query, "Exception resetting autocommit", e); } } closeResultSet(resultSet); } }
From source file:com.tascape.reactor.report.MySqlBaseBean.java
public void importJson(JSONObject json) throws NamingException, SQLException { JSONObject sr = json.getJSONObject("suite_result"); String srid = sr.getString(SuiteResult.SUITE_RESULT_ID); LOG.debug("srid {}", srid); try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + SuiteResult.TABLE_NAME + " WHERE " + SuiteResult.SUITE_RESULT_ID + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid);/*from w w w. j a v a 2s .c o m*/ ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); if (rs.first()) { LOG.debug("already imported {}", srid); return; } rs.moveToInsertRow(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); rs.updateObject(cn, sr.opt(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); LOG.debug("sr imported"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + SuiteProperty.TABLE_NAME + " WHERE " + SuiteProperty.SUITE_RESULT_ID + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); JSONArray sps = sr.getJSONArray("suite_properties"); int len = sps.length(); for (int i = 0; i < len; i++) { rs.moveToInsertRow(); JSONObject tr = sps.getJSONObject(i); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); if (SuiteProperty.SUITE_PROPERTY_ID.equals(cn)) { continue; } rs.updateObject(cn, tr.get(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } LOG.debug("sps imported"); } JSONArray trs = sr.getJSONArray("case_results"); int len = trs.length(); try (Connection conn = this.getConnection()) { String sql = String.format("SELECT * FROM %s WHERE %s=? AND %s=? AND %s=? AND %s=? AND %s=?;", TaskCase.TABLE_NAME, TaskCase.SUITE_CLASS, TaskCase.CASE_CLASS, TaskCase.CASE_METHOD, TaskCase.CASE_DATA_INFO, TaskCase.CASE_DATA); PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setMaxRows(1); for (int i = 0; i < len; i++) { JSONObject tr = trs.getJSONObject(i); stmt.setString(1, tr.getString(TaskCase.SUITE_CLASS)); stmt.setString(2, tr.getString(TaskCase.CASE_CLASS)); stmt.setString(3, tr.getString(TaskCase.CASE_METHOD)); stmt.setString(4, tr.getString(TaskCase.CASE_DATA_INFO)); stmt.setString(5, tr.getString(TaskCase.CASE_DATA)); ResultSet rs = stmt.executeQuery(); if (!rs.first()) { rs.moveToInsertRow(); rs.updateString(TaskCase.SUITE_CLASS, tr.getString(TaskCase.SUITE_CLASS)); rs.updateString(TaskCase.CASE_CLASS, tr.getString(TaskCase.CASE_CLASS)); rs.updateString(TaskCase.CASE_METHOD, tr.getString(TaskCase.CASE_METHOD)); rs.updateString(TaskCase.CASE_DATA_INFO, tr.getString(TaskCase.CASE_DATA_INFO)); rs.updateString(TaskCase.CASE_DATA, tr.getString(TaskCase.CASE_DATA)); rs.insertRow(); rs.last(); rs.updateRow(); rs = stmt.executeQuery(); rs.first(); } tr.put(TaskCase.TASK_CASE_ID, rs.getLong(TaskCase.TASK_CASE_ID)); } LOG.debug("tcid updated"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + CaseResult.TABLE_NAME + " WHERE " + CaseResult.SUITE_RESULT + " = ?;"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setString(1, srid); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < len; i++) { rs.moveToInsertRow(); JSONObject tr = trs.getJSONObject(i); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); rs.updateObject(cn, tr.opt(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } LOG.debug("crs imported"); } try (Connection conn = this.getConnection()) { String sql = "SELECT * FROM " + CaseResultMetric.TABLE_NAME + ";"; PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setMaxRows(1); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < len; i++) { JSONArray jarr = trs.getJSONObject(i).optJSONArray("CASE_result_metrics"); if (jarr == null) { continue; } int l = jarr.length(); for (int j = 0; j < l; j++) { JSONObject trm = jarr.getJSONObject(j); rs.moveToInsertRow(); for (int col = 1; col <= rsmd.getColumnCount(); col++) { String cn = rsmd.getColumnLabel(col); if (cn.equals(CaseResultMetric.CASE_RESULT_METRIC_ID)) { continue; } rs.updateObject(cn, trm.get(cn)); } rs.insertRow(); rs.last(); rs.updateRow(); } } LOG.debug("crms imported"); } }
From source file:com.hangum.tadpole.rdb.core.editors.main.composite.ResultSetComposite.java
/** * ./*from www .j a va2 s . c om*/ * * @param reqQuery * @param queryTimeOut * @param strUserEmail * @param intSelectLimitCnt * @param intStartCnt * @param strNullValue * @return * @throws Exception */ public QueryExecuteResultDTO runSelect(final RequestQuery reqQuery, final int queryTimeOut, final String strUserEmail, final int intSelectLimitCnt, final int intStartCnt) throws Exception { String strSQL = reqQuery.getSql(); if (!PermissionChecker.isExecute(getDbUserRoleType(), getUserDB(), strSQL)) { throw new Exception(Messages.get().MainEditor_21); } if (logger.isDebugEnabled()) logger.debug("==> real execute query : " + strSQL); tadpole_system_message = ""; QueryExecuteResultDTO queryResultDAO = null; // ?? ??? . IMainEditorExtension[] extensions = getRdbResultComposite().getMainEditor().getMainEditorExtions(); if (extensions != null) { for (IMainEditorExtension iMainEditorExtension : extensions) { String strCostumSQL = iMainEditorExtension.sqlCostume(strSQL); if (!strCostumSQL.equals(strSQL)) { if (logger.isDebugEnabled()) logger.debug("** extension costume sql is : " + strCostumSQL); //$NON-NLS-1$ strSQL = strCostumSQL; } } } // ?? ??? . ResultSet resultSet = null; java.sql.Connection javaConn = null; Statement statement = null; PreparedStatement preparedStatement = null; try { if (DBGroupDefine.TAJO_GROUP == getUserDB().getDBGroup()) { javaConn = ConnectionPoolManager.getDataSource(getUserDB()).getConnection(); } else { if (reqQuery.isAutoCommit()) { SqlMapClient client = TadpoleSQLManager.getInstance(getUserDB()); javaConn = client.getDataSource().getConnection(); } else { javaConn = TadpoleSQLTransactionManager.getInstance(strUserEmail, getUserDB()); } } if (javaConn == null) { throw new Exception("Cann't create session. Please check system."); } // if statement type is prepared statement? if (reqQuery.getSqlStatementType() == SQL_STATEMENT_TYPE.NONE) { statement = javaConn.createStatement(); statement.setFetchSize(intSelectLimitCnt); if (DBGroupDefine.HIVE_GROUP != getUserDB().getDBGroup()) { statement.setQueryTimeout(queryTimeOut); statement.setMaxRows(intSelectLimitCnt); } // check stop thread esCheckStop = Executors.newSingleThreadExecutor(); CheckStopThread cst = new CheckStopThread(statement); cst.setName("TDB Query Stop checker"); //$NON-NLS-1$ esCheckStop.execute(cst); // execute query execServiceQuery = Executors.newSingleThreadExecutor(); if (intStartCnt == 0) { resultSet = _runSQLSelect(statement, strSQL); } else { strSQL = PartQueryUtil.makeSelect(getUserDB(), strSQL, intStartCnt, intSelectLimitCnt); if (logger.isDebugEnabled()) logger.debug("part sql called : " + strSQL); resultSet = _runSQLSelect(statement, strSQL); } } else if (reqQuery.getSqlStatementType() == SQL_STATEMENT_TYPE.PREPARED_STATEMENT) { preparedStatement = javaConn.prepareStatement(strSQL); preparedStatement.setFetchSize(intSelectLimitCnt); if (DBGroupDefine.HIVE_GROUP != getUserDB().getDBGroup()) { preparedStatement.setQueryTimeout(queryTimeOut); preparedStatement.setMaxRows(intSelectLimitCnt); } // check stop thread esCheckStop = Executors.newSingleThreadExecutor(); CheckStopThread cst = new CheckStopThread(preparedStatement); cst.setName("TDB Query Stop checker"); //$NON-NLS-1$ esCheckStop.execute(cst); // execute query execServiceQuery = Executors.newSingleThreadExecutor(); if (intStartCnt == 0) { resultSet = _runSQLSelect(preparedStatement, reqQuery.getStatementParameter()); } else { strSQL = PartQueryUtil.makeSelect(getUserDB(), strSQL, intStartCnt, intSelectLimitCnt); if (logger.isDebugEnabled()) logger.debug("part sql called : " + strSQL); resultSet = _runSQLSelect(preparedStatement, reqQuery.getStatementParameter()); } } queryResultDAO = new QueryExecuteResultDTO(getUserDB(), reqQuery.getSql(), true, resultSet, intSelectLimitCnt, intStartCnt); if (resultSet == null) { if (StringUtils.isEmpty(StringUtils.deleteWhitespace(tadpole_system_message))) { tadpole_system_message = CMD_COMPLETE_MSG; } } queryResultDAO.setQueryMsg(tadpole_system_message); } catch (Exception e) { throw e; } finally { isCheckRunning = false; try { if (preparedStatement != null) preparedStatement.close(); } catch (Exception e) { } try { if (statement != null) statement.close(); } catch (Exception e) { } try { if (resultSet != null) resultSet.close(); } catch (Exception e) { } if (reqQuery.isAutoCommit()) { try { if (javaConn != null) javaConn.close(); } catch (Exception e) { } } } return queryResultDAO; }
From source file:nl.nn.adapterframework.jdbc.JdbcQuerySenderBase.java
protected String executeSelectQuery(PreparedStatement statement, Object blobSessionVar, Object clobSessionVar, HttpServletResponse response, String contentType, String contentDisposition) throws SenderException { ResultSet resultset = null;/*w ww . j a va 2s . c o m*/ try { if (getMaxRows() > 0) { statement.setMaxRows(getMaxRows() + (getStartRow() > 1 ? getStartRow() - 1 : 0)); } log.debug(getLogPrefix() + "executing a SELECT SQL command"); resultset = statement.executeQuery(); if (getStartRow() > 1) { resultset.absolute(getStartRow() - 1); log.debug(getLogPrefix() + "Index set at position: " + resultset.getRow()); } return getResult(resultset, blobSessionVar, clobSessionVar, response, contentType, contentDisposition); } catch (SQLException sqle) { throw new SenderException(getLogPrefix() + "got exception executing a SELECT SQL command", sqle); } catch (JdbcException e) { throw new SenderException(getLogPrefix() + "got exception executing a SELECT SQL command", e); } catch (IOException e) { throw new SenderException(getLogPrefix() + "got exception executing a SELECT SQL command", e); } catch (JMSException e) { throw new SenderException(getLogPrefix() + "got exception executing a SELECT SQL command", e); } finally { try { if (resultset != null) { resultset.close(); } } catch (SQLException e) { log.warn(new SenderException(getLogPrefix() + "got exception closing resultset", e)); } } }
From source file:no.polaric.aprsdb.MyDBSession.java
/** * Get points that were transmitted via a certain digipeater during a certain time span. *///w ww . ja v a 2 s . co m public DbList<TPoint> getPointsVia(String digi, Reference uleft, Reference lright, java.util.Date from, java.util.Date to) throws java.sql.SQLException { _log.debug("MyDbSession", "getPointsVia: " + digi + ", " + df.format(from) + " - " + df.format(to)); PreparedStatement stmt = getCon().prepareStatement( " SELECT DISTINCT position " + " FROM \"AprsPacket\" p, \"PosReport\" r " + " WHERE p.src=r.src " + " AND p.time=r.rtime " + " AND (substring(p.path, '([^,\\*]+).*\\*.*')=? OR " + " (substring(p.ipath, 'qAR,([^,\\*]+).*')=? AND p.path !~ '.*\\*.*')) " + " AND position && ST_MakeEnvelope(?, ?, ?, ?, 4326) " + " AND p.time > ? AND p.time < ? LIMIT 10000", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.setString(1, digi); stmt.setString(2, digi); LatLng ul = uleft.toLatLng(); LatLng lr = lright.toLatLng(); stmt.setDouble(3, ul.getLng()); stmt.setDouble(4, ul.getLat()); stmt.setDouble(5, lr.getLng()); stmt.setDouble(6, lr.getLat()); stmt.setTimestamp(7, date2ts(from)); stmt.setTimestamp(8, date2ts(to)); stmt.setMaxRows(10000); return new DbList(stmt.executeQuery(), rs -> { return new TPoint(null, getRef(rs, "position")); }); }
From source file:no.polaric.aprsdb.MyDBSession.java
/** * Get list of signs in a specified geographic area and above a specified scale *///from www .j av a 2 s .co m public DbList<Signs.Item> getSigns(long scale, Reference uleft, Reference lright) throws java.sql.SQLException { PreparedStatement stmt = getCon().prepareStatement( " SELECT s.id AS sid, position, maxscale, url, description, cl.name, s.icon AS sicon, cl.icon AS cicon " + " FROM \"Signs\" s LEFT JOIN \"SignClass\" cl ON s.class=cl.id" + " WHERE maxscale>=? AND position && ST_MakeEnvelope(?, ?, ?, ?, 4326) AND NOT s.hidden" + " LIMIT 200", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); stmt.setLong(1, scale); LatLng ul = uleft.toLatLng(); LatLng lr = lright.toLatLng(); stmt.setDouble(2, ul.getLng()); stmt.setDouble(3, ul.getLat()); stmt.setDouble(4, lr.getLng()); stmt.setDouble(5, lr.getLat()); stmt.setMaxRows(200); return new DbList(stmt.executeQuery(), rs -> { String icon = rs.getString("sicon"); if (icon == null) icon = rs.getString("cicon"); // Item (Reference r, long sc, String ic, String url, String txt) return new Signs.Item(rs.getInt("sid"), getRef(rs, "position"), 0, icon, rs.getString("url"), rs.getString("description")); }); }
From source file:no.polaric.aprsdb.MyDBSession.java
/** * Get trail for a given station and a given time span. *//*from w w w .ja va 2s . co m*/ public DbList<TPoint> getTrail(String src, java.util.Date from, java.util.Date to, boolean rev) throws java.sql.SQLException { _log.debug("MyDbSession", "getTrail: " + src + ", " + df.format(from) + " - " + df.format(to)); PreparedStatement stmt = getCon().prepareStatement( " SELECT * FROM \"PosReport\"" + " WHERE src=? AND time >= ? AND time <= ?" + " ORDER BY time " + (rev ? "DESC" : "ASC") + " LIMIT 500", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.setString(1, src); stmt.setTimestamp(2, date2ts(from)); stmt.setTimestamp(3, date2ts(to)); stmt.setMaxRows(500); return new DbList(stmt.executeQuery(), rs -> { return new TPoint(rs.getTimestamp("time"), getRef(rs, "position")); }); }
From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java
private PreparedStatement createPreapredStatementUsingSetObject(String sql) throws SQLException { PreparedStatement ps = con.prepareStatement(sql); ps.setObject(1, true); //setBoolean ps.setObject(2, true); //setBoolean ps.setObject(3, Short.valueOf("1")); //setShort ps.setObject(4, 2); //setInt ps.setObject(5, 3f); //setFloat ps.setObject(6, Double.valueOf(4)); //setDouble ps.setObject(7, "test'string\""); //setString ps.setObject(8, 5L); //setLong ps.setObject(9, (byte) 1); //setByte ps.setObject(10, (byte) 1); //setByte ps.setString(11, "2012-01-01"); //setString ps.setMaxRows(2); return ps;/* www .j a v a 2 s . c om*/ }
From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java
private PreparedStatement createPreapredStatementUsingSetXXX(String sql) throws SQLException { PreparedStatement ps = con.prepareStatement(sql); ps.setBoolean(1, true); //setBoolean ps.setBoolean(2, true); //setBoolean ps.setShort(3, Short.valueOf("1")); //setShort ps.setInt(4, 2); //setInt ps.setFloat(5, 3f); //setFloat ps.setDouble(6, Double.valueOf(4)); //setDouble ps.setString(7, "test'string\""); //setString ps.setLong(8, 5L); //setLong ps.setByte(9, (byte) 1); //setByte ps.setByte(10, (byte) 1); //setByte ps.setString(11, "2012-01-01"); //setString ps.setMaxRows(2); return ps;// w ww . j a v a2 s . c o m }