List of usage examples for java.sql PreparedStatement getConnection
Connection getConnection() throws SQLException;
Connection
object that produced this Statement
object. From source file:org.hxzon.util.db.springjdbc.StatementCreatorUtils.java
/** * Set the specified PreparedStatement parameter to null, * respecting database-specific peculiarities. *///from ww w . ja v a 2s . com private static void setNull(PreparedStatement ps, int paramIndex, int sqlType, String typeName) throws SQLException { if (sqlType == SqlTypeValue.TYPE_UNKNOWN) { boolean useSetObject = false; Integer sqlTypeToUse = null; DatabaseMetaData dbmd = null; String jdbcDriverName = null; boolean checkGetParameterType = !shouldIgnoreGetParameterType; if (checkGetParameterType && !driversWithNoSupportForGetParameterType.isEmpty()) { try { dbmd = ps.getConnection().getMetaData(); jdbcDriverName = dbmd.getDriverName(); checkGetParameterType = !driversWithNoSupportForGetParameterType.contains(jdbcDriverName); } catch (Throwable ex) { logger.debug("Could not check connection metadata", ex); } } if (checkGetParameterType) { try { sqlTypeToUse = ps.getParameterMetaData().getParameterType(paramIndex); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug( "JDBC 3.0 getParameterType call not supported - using fallback method instead: " + ex); } } } if (sqlTypeToUse == null) { // JDBC driver not compliant with JDBC 3.0 -> proceed with database-specific checks sqlTypeToUse = Types.NULL; try { if (dbmd == null) { dbmd = ps.getConnection().getMetaData(); } if (jdbcDriverName == null) { jdbcDriverName = dbmd.getDriverName(); } if (checkGetParameterType) { driversWithNoSupportForGetParameterType.add(jdbcDriverName); } String databaseProductName = dbmd.getDatabaseProductName(); if (databaseProductName.startsWith("Informix") || jdbcDriverName.startsWith("Microsoft SQL Server")) { useSetObject = true; } else if (databaseProductName.startsWith("DB2") || jdbcDriverName.startsWith("jConnect") || jdbcDriverName.startsWith("SQLServer") || jdbcDriverName.startsWith("Apache Derby")) { sqlTypeToUse = Types.VARCHAR; } } catch (Throwable ex) { logger.debug("Could not check connection metadata", ex); } } if (useSetObject) { ps.setObject(paramIndex, null); } else { ps.setNull(paramIndex, sqlTypeToUse); } } else if (typeName != null) { ps.setNull(paramIndex, sqlType, typeName); } else { ps.setNull(paramIndex, sqlType); } }
From source file:info.naiv.lab.java.tool.sqlite.exporter.component.DataAccess.java
/** * * @param sourceTempl// w w w . ja v a 2 s . com * @param destTempl * @param info * @param valueHandler */ public void copy(final JdbcTemplate sourceTempl, JdbcTemplate destTempl, TableInfo info, final ValueHandler valueHandler) { final Query sq = selectTables.merge(info); Query q = insertSql.merge(info); final List<Field> fields = info.getFields(); q.execute(destTempl, new PreparedStatementCallback<Void>() { @Override public Void doInPreparedStatement(final PreparedStatement ps) throws SQLException, DataAccessException { ps.getConnection().setAutoCommit(false); try { List<Integer> list = sq.query(sourceTempl, new RowMapper<Integer>() { @Override public Integer mapRow(ResultSet rs, int rowNum) throws SQLException { int col = 1; for (Field field : fields) { Object val = valueHandler.handleValue(field, rs); ps.setObject(col, val); } ps.addBatch(); if (rowNum % BATCH_SIZE == 0) { logger.info("execBatch: {}", rowNum); ps.executeBatch(); } return rowNum; } }); int total = list.size(); logger.info("total Batch: {}", total); if (total % BATCH_SIZE != 0) { ps.executeBatch(); } ps.getConnection().commit(); } catch (SQLException | RuntimeException e) { ps.getConnection().rollback(); throw e; } return null; } }); }
From source file:com.reydentx.core.client.MySQLClient.java
public ResultSet excuteStatementQuery(PreparedStatement statement) { Connection conn = null;/*from www . j av a2s . c om*/ try { conn = statement.getConnection(); ResultSet rs = statement.executeQuery(); _pool.returnObject(conn); return rs; } catch (Exception ex) { _logger.error(ex); if (conn != null) { invalidClient(conn); } return null; } }
From source file:com.reydentx.core.client.MySQLClient.java
public int excuteStatementUpdate(PreparedStatement statement) { Connection conn = null;/* w ww . j av a 2s. c o m*/ try { conn = statement.getConnection(); int num = statement.executeUpdate(); _pool.returnObject(conn); return num; } catch (Exception ex) { _logger.error(ex); if (conn != null) { invalidClient(conn); } return 0; } }
From source file:data.DefaultExchanger.java
protected void setClob(PreparedStatement ps, short index, JsonNode node, String column) throws SQLException { String value = node.get(column).textValue(); if (value == null) { ps.setNull(index, Types.CLOB); } else {/*from ww w. j a va 2s .c o m*/ Clob clob = ps.getConnection().createClob(); clob.setString(1, value); ps.setClob(index, clob); } }
From source file:com.demandware.vulnapp.challenge.impl.SQLIChallenge.java
public String handleChallengeRequest(DIVAServletRequestWrapper req) { String output = null;/*w w w.j a va2 s.c o m*/ String query = req.getParameter(SQL_QUERY); String rst = req.getParameter(SQL_RESET); if (!StringUtils.isBlank(rst)) { SessionStorage session = (SessionStorage) req.getInformation(Dictionary.SESSION_STORE_OBJ); String sessionID = session.getToken(); SQLManager.getInstance().removeDBHolder(sessionID); } if (!StringUtils.isBlank(query)) { SessionStorage session = (SessionStorage) req.getInformation(Dictionary.SESSION_STORE_OBJ); String sessionID = session.getToken(); String flag = (String) req.getInformation(Dictionary.FLAG_VALUE); reset(sessionID, flag); DBHolder holder = this.getHolderForSession(sessionID); if (holder != null) { try { PreparedStatement ps = this.makeChallengeQuery(holder, query); output = generateOutputForChallengeQuery(ps); ps.getConnection().close(); } catch (SQLException e) { output = e.getMessage(); } } else { output = "Could not connect to Database. Please log out and log back in"; } } return output; }
From source file:com.yahoo.ycsb.db.PostgreSQLJsonbClient.java
@Override public void cleanup() throws DBException { if (batchSize > 0) { try {/*from w ww.j a v a2 s. c o m*/ // commit un-finished batches for (PreparedStatement st : cachedStatements.values()) { if (!st.getConnection().isClosed() && !st.isClosed() && (numRowsInBatch % batchSize != 0)) { st.executeBatch(); } } } catch (SQLException e) { System.err.println("Error in cleanup execution. " + e); throw new DBException(e); } } try { cleanupAllConnections(); } catch (SQLException e) { System.err.println("Error in closing the connection. " + e); throw new DBException(e); } }
From source file:com.opensymphony.module.propertyset.database.JDBCPropertySet.java
private void setValues(PreparedStatement ps, int type, String key, Object value) throws SQLException, PropertyException { // Patched by Edson Richter for MS SQL Server JDBC Support! String driverName;/* w w w . j a v a 2 s . c o m*/ try { driverName = ps.getConnection().getMetaData().getDriverName().toUpperCase(); } catch (Exception e) { driverName = ""; } ps.setNull(1, Types.VARCHAR); ps.setNull(2, Types.TIMESTAMP); // Patched by Edson Richter for MS SQL Server JDBC Support! // Oracle support suggestion also Michael G. Slack if ((driverName.indexOf("SQLSERVER") >= 0) || (driverName.indexOf("ORACLE") >= 0)) { ps.setNull(3, Types.BINARY); } else { ps.setNull(3, Types.BLOB); } ps.setNull(4, Types.FLOAT); ps.setNull(5, Types.NUMERIC); ps.setInt(6, type); ps.setString(7, globalKey); ps.setString(8, key); switch (type) { case PropertySet.BOOLEAN: Boolean boolVal = (Boolean) value; ps.setInt(5, boolVal.booleanValue() ? 1 : 0); break; case PropertySet.DATA: Data data = (Data) value; ps.setBytes(3, data.getBytes()); break; case PropertySet.DATE: Date date = (Date) value; ps.setTimestamp(2, new Timestamp(date.getTime())); break; case PropertySet.DOUBLE: Double d = (Double) value; ps.setDouble(4, d.doubleValue()); break; case PropertySet.INT: Integer i = (Integer) value; ps.setInt(5, i.intValue()); break; case PropertySet.LONG: Long l = (Long) value; ps.setLong(5, l.longValue()); break; case PropertySet.STRING: ps.setString(1, (String) value); break; default: throw new PropertyException("This type isn't supported!"); } }
From source file:edu.ncsa.sstde.indexing.postgis.PostgisIndexer.java
private void writeIndex(CloseableIteration<? extends BindingSet, QueryEvaluationException> iterator, boolean autoCommit) throws SQLException, QueryEvaluationException { PreparedStatement statement = getInsertStatment(); boolean oldAutoCommit = statement.getConnection().getAutoCommit(); statement.getConnection().setAutoCommit(autoCommit); // Object[] varNames = this.getSettings().getIndexGraph().getVarNames() // .toArray(); // int[] types = getSQLTypes(varNames); int cache = 0; int batchsize = this.getSettings().getBatchSize(); long count = 0; DIGEST.reset();//from w ww.ja v a2 s .c o m for (; iterator.hasNext(); cache++) { BindingSet bindingSet = iterator.next(); setInsertValue(this.getVarNames(), this.getSQLTypes(), statement, bindingSet); try { if (autoCommit) { statement.executeUpdate(); } else { statement.addBatch(); } } catch (SQLException e) { e.printStackTrace(); } if (cache > batchsize) { if (!autoCommit) { statement.executeBatch(); statement.getConnection().commit(); } LOG.info(this.name + " " + (count += cache)); cache = 0; } } if (!autoCommit) { statement.getConnection().commit(); } statement.getConnection().setAutoCommit(oldAutoCommit); }
From source file:edu.ncsa.sstde.indexing.postgis.PostgisIndexer.java
private void executeBatch(SailConnection connection, Collection<Statement> candidateStats, int operation) { HashSet<String> addedIDs = new HashSet<String>(); for (Statement statement : candidateStats) { Map<String, Collection<StatementPattern>> patternMap = this.getSettings().getIndexGraph() .getStatementPatternMap(); Collection<StatementPattern> patterns = new HashSet<StatementPattern>(); //check if the triple is indexed by the triple patterns Collection<StatementPattern> p1 = patternMap.get(statement.getSubject().stringValue()); if (p1 != null) { patterns.addAll(p1);/*from w ww. ja va 2 s. c om*/ } Collection<StatementPattern> p2 = patternMap.get(statement.getPredicate().stringValue()); if (p2 != null) { patterns.addAll(p2); } Collection<StatementPattern> p3 = patternMap.get(statement.getObject().stringValue()); if (p3 != null) { patterns.addAll(p3); } if (patterns.size() > 0) { try { PreparedStatement sqlStatement = null; if (operation == OPERATION_ADD) { sqlStatement = getInsertStatment(); } else if (operation == OPERATION_REMOVE) { sqlStatement = getRemoveStatment(); } boolean oldAutoCommit = sqlStatement.getConnection().getAutoCommit(); sqlStatement.getConnection().setAutoCommit(true); for (StatementPattern pattern : patterns) { QueryBindingSet bindingSet = new QueryBindingSet(2); if (!pattern.getSubjectVar().hasValue()) { bindingSet.addBinding(pattern.getSubjectVar().getName(), statement.getSubject()); } if (!pattern.getPredicateVar().hasValue()) { bindingSet.addBinding(pattern.getPredicateVar().getName(), statement.getPredicate()); } if (!pattern.getObjectVar().hasValue()) { bindingSet.addBinding(pattern.getObjectVar().getName(), statement.getObject()); } DIGEST.reset(); if (this.getSettings().getIndexGraph().getPatterns().size() == 1) { if (operation == OPERATION_ADD) { setInsertValue(this.getVarNames(), this.getSQLTypes(), sqlStatement, bindingSet); } else if (operation == OPERATION_REMOVE) { setRemoveValue(this.getVarNames(), sqlStatement, bindingSet); } try { sqlStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } else { CloseableIteration<? extends BindingSet, QueryEvaluationException> iterator = connection .evaluate(this.getSettings().getIndexGraph().getTupleQuery(), null, bindingSet, false); for (; iterator.hasNext();) { BindingSet resultBinding = iterator.next(); if (operation == OPERATION_ADD) { String md5 = setInsertValue(this.getVarNames(), this.getSQLTypes(), sqlStatement, resultBinding); if (!addedIDs.contains(md5)) { addedIDs.add(md5); try { sqlStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } } else if (operation == OPERATION_REMOVE) { setRemoveValue(this.getVarNames(), sqlStatement, resultBinding); try { sqlStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } } } } sqlStatement.getConnection().setAutoCommit(oldAutoCommit); } catch (SQLException e1) { e1.printStackTrace(); } catch (SailException e) { e.printStackTrace(); } catch (QueryEvaluationException e) { e.printStackTrace(); } } } }