List of usage examples for java.sql PreparedStatement getConnection
Connection getConnection() throws SQLException;
Connection
object that produced this Statement
object. From source file:org.apache.synapse.message.store.impl.jdbc.JDBCMessageStore.java
/** * Return number of messages in the store * * @return size - Number of messages//from w w w.j av a 2 s. co m */ @Override public int size() { Connection con = null; ResultSet rs = null; PreparedStatement ps = null; int size = 0; Statement stmt = new Statement("SELECT COUNT(*) FROM " + jdbcConfiguration.getTableName()); try { con = jdbcConfiguration.getConnection(); ps = con.prepareStatement(stmt.getRawStatement()); con = ps.getConnection(); rs = ps.executeQuery(); while (rs.next()) { try { size = rs.getInt(1); } catch (Exception e) { logger.error("Error executing statement : " + stmt.getRawStatement() + " against DataSource : " + jdbcConfiguration.getDSName(), e); break; } } } catch (SQLException e) { logger.error("Error executing statement : " + stmt.getRawStatement() + " against DataSource : " + jdbcConfiguration.getDSName(), e); } finally { close(con, ps, rs); } return size; }
From source file:org.deegree.sqldialect.oracle.OracleGeometryConverter.java
@Override public void setParticle(PreparedStatement stmt, Geometry particle, int paramIndex) throws SQLException { try {/*from w w w. ja v a2 s . co m*/ if (particle == null) { stmt.setNull(paramIndex, Types.STRUCT, "MDSYS.SDO_GEOMETRY"); } else { Geometry compatible = getCompatibleGeometry(particle); // TODO clarify if this was only a wkt/wkb requirement ?! // (background Envelope -> Optimized Rectangles in Oracle are preferred and faster for SDO_RELATE // filters ) // // if ( compatible instanceof Envelope ) { // compatible = compatible.getConvexHull(); // } OracleConnection ocon = getOracleConnection(stmt.getConnection()); Object struct = new SDOGeometryConverter().fromGeometry(ocon, isrid, compatible, true); stmt.setObject(paramIndex, struct); } } catch (Throwable t) { t.printStackTrace(); throw new IllegalArgumentException(); } }
From source file:org.eclipse.ecr.core.storage.sql.jdbc.dialect.DialectPostgreSQL.java
@Override public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column) throws SQLException { switch (column.getJdbcType()) { case Types.VARCHAR: case Types.CLOB: setToPreparedStatementString(ps, index, value, column); return;//w w w. ja v a 2 s . c om case Types.BIT: ps.setBoolean(index, ((Boolean) value).booleanValue()); return; case Types.SMALLINT: ps.setInt(index, ((Long) value).intValue()); return; case Types.INTEGER: case Types.BIGINT: ps.setLong(index, ((Long) value).longValue()); return; case Types.DOUBLE: ps.setDouble(index, ((Double) value).doubleValue()); return; case Types.TIMESTAMP: setToPreparedStatementTimestamp(ps, index, value, column); return; case Types.ARRAY: Array array = createArrayOf(Types.VARCHAR, (Object[]) value, ps.getConnection()); ps.setArray(index, array); return; case Types.OTHER: if (column.getType() == ColumnType.FTSTORED) { ps.setString(index, (String) value); return; } throw new SQLException("Unhandled type: " + column.getType()); default: throw new SQLException("Unhandled JDBC type: " + column.getJdbcType()); } }
From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.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;//from w ww . j a va 2s . 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!"); } if (valueMap == null) valueMap = new HashMap(); if (typeMap == null) typeMap = new HashMap(); valueMap.put(key, value); typeMap.put(key, new Integer(type)); }
From source file:org.jboss.dashboard.database.hibernate.LOBHelper.java
public void oracleNullSafeSet(PreparedStatement statement, Object value, int index, ValueWriter vw) throws HibernateException, SQLException { try {// w w w .ja v a2 s.co m // Invoke by reflection the Oracle classes Class oracleBlobClass = Class.forName(ORACLE_CLASS); Method createTempMethod = getMethod(oracleBlobClass, ORACLE_TEMP_METHOD, Connection.class, Boolean.TYPE, Integer.TYPE); Field durationSession = oracleBlobClass.getField(ORACLE_DURATION__SESSION); Object arglist[] = new Object[3]; Connection conn = statement.getConnection(); arglist[0] = conn; arglist[1] = Boolean.TRUE; arglist[2] = durationSession.get(null); Object tempBlob = null; // Needed to avoid JBoss AS class loading issues... Class connClassInCurrentClassLoader = Class.forName(conn.getClass().getName()); // Direct Oracle connection if (Class.forName(ORACLE_JDBC_ORACLE_CONNECTION).isAssignableFrom(connClassInCurrentClassLoader)) { tempBlob = createTempMethod.invoke(null, arglist); // null is valid because of static method } // JBoss AS data source wrapper connection. else if (WrappedConnection.class.isAssignableFrom(connClassInCurrentClassLoader)) { arglist[0] = ReflectionUtils.invokeMethod(conn, "getUnderlyingConnection", null); tempBlob = createTempMethod.invoke(null, arglist); // null is valid because of static method } // C3P0 pool managed connection. else if (NewProxyConnection.class.isAssignableFrom(connClassInCurrentClassLoader)) { NewProxyConnection castCon = (NewProxyConnection) conn; arglist[0] = C3P0ProxyConnection.RAW_CONNECTION; tempBlob = castCon.rawConnectionOperation(createTempMethod, C3P0ProxyConnection.RAW_CONNECTION, arglist); } // Apache's DBCP pool managed connection. else if (PoolableConnection.class.isAssignableFrom(connClassInCurrentClassLoader)) { arglist[0] = ((PoolableConnection) statement.getConnection()).getDelegate(); tempBlob = createTempMethod.invoke(null, arglist); // null is valid because of static method } else { boolean throwException = true; //check if we are running in websphere try { String wasConnectionWrapper = "com.ibm.ws.rsadapter.jdbc.WSJdbcConnection"; Class wasConnectionWrapperClass = Class.forName(wasConnectionWrapper); if (wasConnectionWrapperClass.isAssignableFrom(connClassInCurrentClassLoader)) { String helperClass = "com.ibm.websphere.rsadapter.WSCallHelper"; Class helper = Class.forName(helperClass); Method nativeConnMethod = helper.getMethod("getNativeConnection", new Class[] { Object.class }); Connection nativeConn = (Connection) nativeConnMethod.invoke(null, conn); if (Class.forName(ORACLE_JDBC_ORACLE_CONNECTION).isAssignableFrom(nativeConn.getClass())) { arglist[0] = nativeConn; tempBlob = createTempMethod.invoke(null, arglist); throwException = false; } } } catch (Throwable e) { e.printStackTrace(); // do nothing } if (throwException) { throw new HibernateException("JDBC connection object must be a oracle.jdbc.OracleConnection " + "a " + WrappedConnection.class.getName() + "a " + PoolableConnection.class.getName() + "or a " + NewProxyConnection.class.getName() + ". Connection class is " + connClassInCurrentClassLoader.getName()); } } Method openMethod = getMethod(oracleBlobClass, ORACLE_OPEN_METHOD, Integer.TYPE, null, null); Field fieldReadWrite = oracleBlobClass.getField(ORACLE_MODE__READWRITE); arglist = new Object[1]; arglist[0] = fieldReadWrite.get(null); //null is valid because of static field openMethod.invoke(tempBlob, arglist); Method getOutputStreamMethod = oracleBlobClass.getDeclaredMethod(ORACLE_GET_BINARY_OUTPUT_STREAM, null); OutputStream os = (OutputStream) getOutputStreamMethod.invoke(tempBlob, null); try { vw.writeValue(os, value); os.flush(); } finally { os.close(); } Method closeMethod = oracleBlobClass.getDeclaredMethod(ORACLE_CLOSE, null); closeMethod.invoke(tempBlob, null); statement.setBlob(index, (Blob) tempBlob); } catch (Exception e) { throw new HibernateException("Error in oracleNullSafeSet", e); } }
From source file:org.kawanfw.sql.servlet.sql.ServerPreparedStatementParameters.java
/** * Set the binary stream using the underlying Blob file uploaded by the * client side/*w w w. ja v a2 s . co m*/ * * @param preparedStatement * The Prepared Statement to execute * @param parameterIndex * the parameter index * @param paramValue * the parameter value (the file name) * @throws SQLException * @throws IOException */ private void setBinaryStream(PreparedStatement preparedStatement, int parameterIndex, String paramValue) throws SQLException, IOException { // Extract the Blob file from the parameter debug("before getFileFromParameter()"); File blobFile = getFileFromParameter(paramValue); blobsOrClobs.add(blobFile); debug("before new BufferedInputStream(new FileInputStream(blobFile))"); // Then update the prepared statement binary stream and we are done! InputStream in = new BufferedInputStream(new FileInputStream(blobFile)); long theLength = blobFile.length(); debug("before preparedStatement.setBinaryStream()"); Connection connection = preparedStatement.getConnection(); String sql = statementHolder.getSqlOrder(); // Test if we are in PostgreSQL with OID column for large file if (PostgreSqlUtil.isPostgreSqlStatementWithOID(connection, sql)) { debug("column is OID! " + parameterIndex); PostgreSqlUtil.setPostgreSqlParameterWithLargeObject(preparedStatement, parameterIndex, in, connection); } else { // We cast theLength, because the long version may not be // implemented by // the driver debug("column is NOT OID " + parameterIndex); preparedStatement.setBinaryStream(parameterIndex, in, (int) theLength); } this.inList.add(in); debug("after preparedStatement.setBinaryStream()"); }
From source file:org.LexGrid.util.sql.DBUtility.java
/** * Sets booleans properly in the LexGrid world. * /*from w w w . j a v a2 s. co m*/ * @param statement * @param colNumber * @param value * @param isSqlLite * - using sqlLite tables? Set to true if the answer is yes. * @param databaseType * - optional. Set to null or "" if you don't know it. * @throws SQLException */ public static void setBooleanOnPreparedStatment(PreparedStatement statement, int colNumber, Boolean value, boolean isSqlLite, String databaseType) throws SQLException { if (databaseType == null || databaseType.length() == 0) { databaseType = statement.getConnection().getMetaData().getDatabaseProductName(); } // This has been tested (and works correctly) on mysql (using tinyint // with 1 and 0), postgres (using // bool) // and Access using both a Text of (True or False) and yes/no. if (value == null) { // mysql lite (on access) uses yesno's for booleans (which don't // support null), while regular sql // doesn't. if (isSqlLite && databaseType.equals("ACCESS")) { statement.setBoolean(colNumber, false); } // the new postgres driver doesn't allow you to use the setString to // null trick. else if (databaseType.equals("PostgreSQL")) { statement.setNull(colNumber, java.sql.Types.BOOLEAN); } // most other databases let you set null on a string, even if it // isn't a string type. else { statement.setString(colNumber, null); } } else { // sql on format on access, and mysql both use strings instead of // booleans (to support null) if ((databaseType.equals("ACCESS") && !isSqlLite)) { statement.setString(colNumber, value.booleanValue() + ""); } else if (databaseType.equals("MySQL")) { statement.setInt(colNumber, (value.booleanValue() ? 1 : 0)); } else { statement.setBoolean(colNumber, value.booleanValue()); } } }
From source file:org.nuxeo.ecm.core.storage.sql.db.dialect.DialectPostgreSQL.java
@Override public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column) throws SQLException { switch (column.getJdbcType()) { case Types.VARCHAR: case Types.CLOB: String v;//from w w w. j a v a2s. co m if (column.getType() == ColumnType.BLOBID) { v = ((Binary) value).getDigest(); } else { v = (String) value; } ps.setString(index, v); break; case Types.BIT: ps.setBoolean(index, ((Boolean) value).booleanValue()); return; case Types.SMALLINT: ps.setInt(index, ((Long) value).intValue()); return; case Types.INTEGER: case Types.BIGINT: ps.setLong(index, ((Long) value).longValue()); return; case Types.DOUBLE: ps.setDouble(index, ((Double) value).doubleValue()); return; case Types.TIMESTAMP: Calendar cal = (Calendar) value; Timestamp ts = new Timestamp(cal.getTimeInMillis()); ps.setTimestamp(index, ts, cal); // cal passed for timezone return; case Types.ARRAY: Array array = createArrayOf(Types.VARCHAR, (Object[]) value, ps.getConnection()); ps.setArray(index, array); return; case Types.OTHER: if (column.getType() == ColumnType.FTSTORED) { ps.setString(index, (String) value); return; } throw new SQLException("Unhandled type: " + column.getType()); default: throw new SQLException("Unhandled JDBC type: " + column.getJdbcType()); } }
From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectPostgreSQL.java
@Override public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column) throws SQLException { switch (column.getJdbcType()) { case Types.VARCHAR: case Types.CLOB: setToPreparedStatementString(ps, index, value, column); return;/*from w w w . j a v a2 s . co m*/ case Types.BIT: ps.setBoolean(index, ((Boolean) value).booleanValue()); return; case Types.SMALLINT: ps.setInt(index, ((Long) value).intValue()); return; case Types.INTEGER: case Types.BIGINT: ps.setLong(index, ((Number) value).longValue()); return; case Types.DOUBLE: ps.setDouble(index, ((Double) value).doubleValue()); return; case Types.TIMESTAMP: ps.setTimestamp(index, getTimestampFromCalendar((Calendar) value)); return; case Types.ARRAY: int jdbcBaseType = column.getJdbcBaseType(); String jdbcBaseTypeName = column.getSqlBaseTypeString(); if (jdbcBaseType == Types.TIMESTAMP) { value = getTimestampFromCalendar((Serializable[]) value); } Array array = ps.getConnection().createArrayOf(jdbcBaseTypeName, (Object[]) value); ps.setArray(index, array); return; case Types.OTHER: ColumnType type = column.getType(); if (type.isId()) { setId(ps, index, value); return; } else if (type == ColumnType.FTSTORED) { ps.setString(index, (String) value); return; } throw new SQLException("Unhandled type: " + column.getType()); default: throw new SQLException("Unhandled JDBC type: " + column.getJdbcType()); } }
From source file:org.openbravo.database.ConnectionProviderImpl.java
public void releasePreparedStatement(PreparedStatement preparedStatement) throws SQLException { if (preparedStatement == null) return;//from w w w . j a va2s.co m Connection conn = null; try { conn = preparedStatement.getConnection(); preparedStatement.close(); releaseConnection(conn); } catch (SQLException e) { log4j.error("releasePreparedStatement: " + e); releaseConnection(conn); throw e; } }