List of usage examples for java.sql PreparedStatement setDate
void setDate(int parameterIndex, java.sql.Date x) throws SQLException;
java.sql.Date
value using the default time zone of the virtual machine that is running the application. From source file:org.apache.phoenix.end2end.index.IndexExpressionIT.java
/** * Adds a row to the index data table/*from ww w . j a v a 2 s .c om*/ * * @param i * row number */ private void insertRow(PreparedStatement stmt, int i) throws SQLException { // insert row stmt.setString(1, "varchar" + String.valueOf(i)); stmt.setString(2, "char" + String.valueOf(i)); stmt.setInt(3, i); stmt.setLong(4, i); stmt.setBigDecimal(5, new BigDecimal(i * 0.5d)); Date date = new Date(DateUtil.parseDate("2015-01-01 00:00:00").getTime() + (i - 1) * NUM_MILLIS_IN_DAY); stmt.setDate(6, date); stmt.setString(7, "a.varchar" + String.valueOf(i)); stmt.setString(8, "a.char" + String.valueOf(i)); stmt.setInt(9, i); stmt.setLong(10, i); stmt.setBigDecimal(11, new BigDecimal(i * 0.5d)); stmt.setDate(12, date); stmt.setString(13, "b.varchar" + String.valueOf(i)); stmt.setString(14, "b.char" + String.valueOf(i)); stmt.setInt(15, i); stmt.setLong(16, i); stmt.setBigDecimal(17, new BigDecimal(i * 0.5d)); stmt.setDate(18, date); stmt.executeUpdate(); }
From source file:org.brucalipto.sqlutil.SQLManager.java
protected int executeSimpleQuery(final String preparedStatement, final SQLParameter[] params) { final SQLParameter[] parameters; if (params == null) { parameters = new SQLParameter[0]; log.debug("Going to execute a query without parameters."); } else {/*from w ww . ja v a2 s .co m*/ parameters = (SQLParameter[]) params.clone(); } Connection dbConn = null; PreparedStatement pstmt = null; try { if (this.dataSource != null) { dbConn = this.dataSource.getConnection(); } else { dbConn = this.connection; } pstmt = dbConn.prepareStatement(preparedStatement); for (int i = 0; i < parameters.length; i++) { final SQLParameter param = parameters[i]; log.debug((i + 1) + ") Going to add parameter " + param); final int sqlType = param.getSqlType(); final Object paramValue = param.getValue(); if (paramValue == null) { pstmt.setNull(i + 1, sqlType); continue; } switch (sqlType) { case Types.VARCHAR: pstmt.setString(i + 1, (String) paramValue); break; case Types.INTEGER: if (paramValue instanceof Integer) { pstmt.setInt(i + 1, ((Integer) paramValue).intValue()); } else if (paramValue instanceof Long) { pstmt.setLong(i + 1, ((Long) paramValue).longValue()); } break; case Types.DATE: pstmt.setDate(i + 1, (Date) paramValue); break; case Types.BOOLEAN: pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue()); break; case Types.CHAR: pstmt.setString(i + 1, ((Character) paramValue).toString()); break; case Types.DOUBLE: pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue()); break; case Types.FLOAT: pstmt.setFloat(i + 1, ((Float) paramValue).floatValue()); break; case Types.TIMESTAMP: pstmt.setTimestamp(i + 1, (Timestamp) paramValue); break; default: pstmt.setObject(i + 1, paramValue); break; } } int result = pstmt.executeUpdate(); log.debug("Prepared statement '" + preparedStatement + "' correctly executed (" + result + ")"); return result; } catch (SQLException e) { log.error("Error executing prepared statement '" + preparedStatement + "'", e); } catch (Exception e) { log.error("Error executing prepared statement '" + preparedStatement + "'", e); } finally { closeResources(pstmt, dbConn); } return -1; }
From source file:org.brucalipto.sqlutil.SQLManager.java
/** * Method useful for SQL SELECT//w w w. j a v a 2 s .c om * @param preparedStatement The prepared statement to execute * @param params List of {@link SQLParameter} to use to complete the prepared statement * @param outputSQLType A java.sql.Types type of return value * @return The {@link SPParameter} containing the returned value */ public SQLParameter simpleSelect(final String preparedStatement, SQLParameter[] params, final int outputSQLType) { final SQLParameter[] parameters; if (params == null) { parameters = new SQLParameter[0]; log.debug("Going to execute a query without parameters."); } else { parameters = (SQLParameter[]) params.clone(); } Connection dbConn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { if (this.dataSource != null) { dbConn = this.dataSource.getConnection(); } else { dbConn = this.connection; } pstmt = dbConn.prepareStatement(preparedStatement); for (int i = 0; i < parameters.length; i++) { final SQLParameter param = parameters[i]; log.debug((i + 1) + ") Going to add parameter " + param); final int sqlType = param.getSqlType(); final Object paramValue = param.getValue(); if (paramValue == null) { pstmt.setNull(i + 1, sqlType); continue; } switch (sqlType) { case Types.VARCHAR: pstmt.setString(i + 1, (String) paramValue); break; case Types.INTEGER: if (paramValue instanceof Integer) { pstmt.setInt(i + 1, ((Integer) paramValue).intValue()); } else if (paramValue instanceof Long) { pstmt.setLong(i + 1, ((Long) paramValue).longValue()); } break; case Types.DATE: pstmt.setDate(i + 1, (Date) paramValue); break; case Types.BOOLEAN: pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue()); break; case Types.CHAR: pstmt.setString(i + 1, ((Character) paramValue).toString()); break; case Types.DOUBLE: pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue()); break; case Types.FLOAT: pstmt.setFloat(i + 1, ((Float) paramValue).floatValue()); break; case Types.TIMESTAMP: pstmt.setTimestamp(i + 1, (Timestamp) paramValue); break; default: pstmt.setObject(i + 1, paramValue); break; } } rs = pstmt.executeQuery(); log.debug("Prepared statement '" + preparedStatement + "' succesfully executed!"); while (rs.next()) { return new SQLParameter(outputSQLType, (Serializable) rs.getObject(1)); } log.info("Prepared statement '" + preparedStatement + "' returned '0' rows"); } catch (SQLException e) { log.error("Error executing prepared statement '" + preparedStatement + "'", e); } catch (Exception e) { log.error("Error executing prepared statement '" + preparedStatement + "'", e); } finally { closeResources(rs, pstmt, dbConn); } return new SQLParameter(outputSQLType, null); }
From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCRatingsDAO.java
public void addRating(ResourceImpl resourceImpl, String userID, int rating) throws RegistryException { JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection(); PreparedStatement ps1 = null, ps2 = null, ps3 = null; ResultSet result = null;//from w ww. j a v a 2 s.co m try { String sql1 = "INSERT INTO REG_RATING (REG_RATING, REG_USER_ID, REG_RATED_TIME, " + "REG_TENANT_ID) VALUES (?,?,?,?)"; String sql2 = "SELECT MAX(REG_ID) FROM REG_RATING"; String dbProductName = conn.getMetaData().getDatabaseProductName(); boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName); if (returnsGeneratedKeys) { ps1 = conn.prepareStatement(sql1, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, DatabaseConstants.ID_FIELD) }); } else { ps1 = conn.prepareStatement(sql1); } ps1.setInt(1, rating); ps1.setString(2, userID); long now = System.currentTimeMillis(); ps1.setDate(3, new Date(now)); ps1.setInt(4, CurrentSession.getTenantId()); if (returnsGeneratedKeys) { ps1.executeUpdate(); result = ps1.getGeneratedKeys(); } else { synchronized (ADD_RATING_LOCK) { ps1.executeUpdate(); ps2 = conn.prepareStatement(sql2); result = ps2.executeQuery(); } } if (result.next()) { int rateID = result.getInt(1); String sql3 = "INSERT INTO REG_RESOURCE_RATING (REG_RATING_ID, REG_PATH_ID, " + "REG_RESOURCE_NAME, REG_TENANT_ID) " + "VALUES(?,?,?,?)"; ps3 = conn.prepareStatement(sql3); ps3.setInt(1, rateID); ps3.setInt(2, resourceImpl.getPathID()); ps3.setString(3, resourceImpl.getName()); ps3.setInt(4, CurrentSession.getTenantId()); ps3.executeUpdate(); } } catch (SQLException e) { String msg = "Failed to rate resource " + resourceImpl.getPath() + " with rating " + rating + ". " + e.getMessage(); log.error(msg, e); throw new RegistryException(msg, e); } finally { try { try { if (result != null) { result.close(); } } finally { try { if (ps1 != null) { ps1.close(); } } finally { try { if (ps2 != null) { ps2.close(); } } finally { if (ps3 != null) { ps3.close(); } } } } } catch (SQLException ex) { String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } }
From source file:org.brucalipto.sqlutil.SQLManager.java
/** * Method useful for SQL SELECT//from w ww. ja v a 2 s . c om * @param preparedStatement The prepared statement to execute * @param parameters List of {@link SQLParameter} to use to complete the prepared statement * @return Returns a RowSetDynaClass containing returned rows * @throws SQLException */ public RowSetDynaClass dynaSelect(final String preparedStatement, final SQLParameter[] params) throws SQLException { final long elapsedTime = System.currentTimeMillis(); SQLParameter[] parameters; if (params == null) { parameters = new SQLParameter[0]; log.debug("Going to execute a query without parameters."); } else { parameters = (SQLParameter[]) params.clone(); } Connection dbConn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { if (this.dataSource != null) { dbConn = this.dataSource.getConnection(); } else { dbConn = this.connection; } pstmt = dbConn.prepareStatement(preparedStatement); for (int i = 0; i < parameters.length; i++) { final SQLParameter param = parameters[i]; log.debug((i + 1) + ") Going to add parameter " + param); final int sqlType = param.getSqlType(); final Object paramValue = param.getValue(); if (paramValue == null) { pstmt.setNull(i + 1, sqlType); continue; } switch (sqlType) { case Types.VARCHAR: pstmt.setString(i + 1, (String) paramValue); break; case Types.INTEGER: if (paramValue instanceof Integer) { pstmt.setInt(i + 1, ((Integer) paramValue).intValue()); } else if (paramValue instanceof Long) { pstmt.setLong(i + 1, ((Long) paramValue).longValue()); } break; case Types.DATE: pstmt.setDate(i + 1, (Date) paramValue); break; case Types.BOOLEAN: pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue()); break; case Types.CHAR: pstmt.setString(i + 1, ((Character) paramValue).toString()); break; case Types.DOUBLE: pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue()); break; case Types.FLOAT: pstmt.setFloat(i + 1, ((Float) paramValue).floatValue()); break; case Types.TIMESTAMP: pstmt.setTimestamp(i + 1, (Timestamp) paramValue); break; default: pstmt.setObject(i + 1, paramValue); break; } } rs = pstmt.executeQuery(); RowSetDynaClass rowSetDynaClass = new RowSetDynaClass(rs, false); if (log.isDebugEnabled()) { log.debug("Prepared statement '" + preparedStatement + "' returned '" + rowSetDynaClass.getRows().size() + "' rows in '" + (System.currentTimeMillis() - elapsedTime) + "' millis with following properties:"); DynaProperty[] properties = rowSetDynaClass.getDynaProperties(); for (int i = 0; i < properties.length; i++) { log.debug("Name: '" + properties[i].getName() + "'; Type: '" + properties[i].getType().getName() + "'"); } } return rowSetDynaClass; } catch (SQLException e) { log.error("Error executing prepared statement '" + preparedStatement + "'", e); throw e; } finally { closeResources(rs, pstmt, dbConn); } }
From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCTagsDAO.java
public void addTaggings(ResourceImpl resource, TaggingDO[] taggingDOs) throws RegistryException { JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection(); long now = System.currentTimeMillis(); for (TaggingDO taggingDO : taggingDOs) { PreparedStatement ps = null; PreparedStatement ps2 = null; ResultSet result = null;/*ww w .j a va2 s . co m*/ try { String sql = "INSERT INTO REG_TAG (REG_TAG_NAME, REG_USER_ID, REG_TAGGED_TIME, " + "REG_TENANT_ID) VALUES (?,?,?,?)"; String dbProductName = conn.getMetaData().getDatabaseProductName(); ps = conn.prepareStatement(sql, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "REG_ID") }); ps.setString(1, taggingDO.getTagName()); ps.setString(2, taggingDO.getTaggedUserName()); ps.setDate(3, new Date(now)); ps.setInt(4, CurrentSession.getTenantId()); ps.executeUpdate(); result = ps.getGeneratedKeys(); if (result.next()) { int tagId = result.getInt(1); String sql2 = "INSERT INTO REG_RESOURCE_TAG (REG_TAG_ID, REG_PATH_ID, " + "REG_RESOURCE_NAME, REG_TENANT_ID) " + "VALUES(?,?,?,?)"; ps2 = conn.prepareStatement(sql2); ps2.setInt(1, tagId); ps2.setInt(2, resource.getPathID()); ps2.setString(3, resource.getName()); ps2.setInt(4, CurrentSession.getTenantId()); ps2.executeUpdate(); } } catch (SQLException e) { String msg = "Failed to add tags to resource " + resource.getPath() + ". " + e.getMessage(); log.error(msg, e); throw new RegistryException(msg, e); } finally { // closing open prepared statements & result sets before moving on to next iteration try { try { if (result != null) { result.close(); } } finally { try { if (ps != null) { ps.close(); } } finally { if (ps2 != null) { ps2.close(); } } } } catch (SQLException ex) { String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } } }
From source file:org.apache.phoenix.end2end.DateTimeIT.java
@Test public void testDateInList() throws Exception { String query = "SELECT entity_id FROM " + this.tableName + " WHERE a_date IN (?,?) AND a_integer < 4"; PreparedStatement statement = conn.prepareStatement(query); statement.setDate(1, new Date(0)); statement.setDate(2, date);/*w ww .ja v a 2s.c o m*/ ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(ROW1, rs.getString(1)); assertFalse(rs.next()); }
From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCTagsVersionDAO.java
/** * Method to persist a tag.//from w ww.j a v a 2 s. c om * * @param resource the resource * @param userID the id of the user who added the tag. * @param tagName the name of tag to be persisted. * * @throws RegistryException if some error occurs while adding a tag */ public void addTagging(String tagName, ResourceImpl resource, String userID) throws RegistryException { JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection(); PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; ResultSet result = null; try { String sql1 = "INSERT INTO REG_TAG (REG_TAG_NAME, REG_USER_ID, REG_TAGGED_TIME, " + "REG_TENANT_ID) VALUES (?,?,?,?)"; String sql2 = "SELECT MAX(REG_ID) FROM REG_TAG"; long now = System.currentTimeMillis(); String dbProductName = conn.getMetaData().getDatabaseProductName(); boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName); if (returnsGeneratedKeys) { ps1 = conn.prepareStatement(sql1, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, DatabaseConstants.ID_FIELD) }); } else { ps1 = conn.prepareStatement(sql1); } ps1.setString(1, tagName); ps1.setString(2, userID); ps1.setDate(3, new Date(now)); ps1.setInt(4, CurrentSession.getTenantId()); if (returnsGeneratedKeys) { ps1.executeUpdate(); result = ps1.getGeneratedKeys(); } else { synchronized (ADD_TAG_LOCK) { ps1.executeUpdate(); ps2 = conn.prepareStatement(sql2); result = ps2.executeQuery(); } } if (result.next()) { int tagId = result.getInt(1); String sql3 = "INSERT INTO REG_RESOURCE_TAG (REG_TAG_ID, REG_VERSION, REG_TENANT_ID) " + "VALUES(?,?,?)"; ps3 = conn.prepareStatement(sql3); ps3.setInt(1, tagId); ps3.setLong(2, resource.getVersionNumber()); ps3.setInt(3, CurrentSession.getTenantId()); ps3.executeUpdate(); } } catch (SQLException e) { String msg = "Failed to add tag " + tagName + " to resource " + resource.getPath() + " by user " + userID + ". " + e.getMessage(); log.error(msg, e); throw new RegistryException(msg, e); } finally { try { try { if (result != null) { result.close(); } } finally { try { if (ps1 != null) { ps1.close(); } } finally { try { if (ps2 != null) { ps2.close(); } } finally { if (ps3 != null) { ps3.close(); } } } } } catch (SQLException ex) { String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } }
From source file:org.springframework.jdbc.core.StatementCreatorUtils.java
private static void setValue(PreparedStatement ps, int paramIndex, int sqlType, @Nullable String typeName, @Nullable Integer scale, Object inValue) throws SQLException { if (inValue instanceof SqlTypeValue) { ((SqlTypeValue) inValue).setTypeValue(ps, paramIndex, sqlType, typeName); } else if (inValue instanceof SqlValue) { ((SqlValue) inValue).setValue(ps, paramIndex); } else if (sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR) { ps.setString(paramIndex, inValue.toString()); } else if (sqlType == Types.NVARCHAR || sqlType == Types.LONGNVARCHAR) { ps.setNString(paramIndex, inValue.toString()); } else if ((sqlType == Types.CLOB || sqlType == Types.NCLOB) && isStringValue(inValue.getClass())) { String strVal = inValue.toString(); if (strVal.length() > 4000) { // Necessary for older Oracle drivers, in particular when running against an Oracle 10 database. // Should also work fine against other drivers/databases since it uses standard JDBC 4.0 API. if (sqlType == Types.NCLOB) { ps.setNClob(paramIndex, new StringReader(strVal), strVal.length()); } else { ps.setClob(paramIndex, new StringReader(strVal), strVal.length()); }/*from w w w . j av a2s. c o m*/ return; } else { // Fallback: setString or setNString binding if (sqlType == Types.NCLOB) { ps.setNString(paramIndex, strVal); } else { ps.setString(paramIndex, strVal); } } } else if (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) { if (inValue instanceof BigDecimal) { ps.setBigDecimal(paramIndex, (BigDecimal) inValue); } else if (scale != null) { ps.setObject(paramIndex, inValue, sqlType, scale); } else { ps.setObject(paramIndex, inValue, sqlType); } } else if (sqlType == Types.BOOLEAN) { if (inValue instanceof Boolean) { ps.setBoolean(paramIndex, (Boolean) inValue); } else { ps.setObject(paramIndex, inValue, Types.BOOLEAN); } } else if (sqlType == Types.DATE) { if (inValue instanceof java.util.Date) { if (inValue instanceof java.sql.Date) { ps.setDate(paramIndex, (java.sql.Date) inValue); } else { ps.setDate(paramIndex, new java.sql.Date(((java.util.Date) inValue).getTime())); } } else if (inValue instanceof Calendar) { Calendar cal = (Calendar) inValue; ps.setDate(paramIndex, new java.sql.Date(cal.getTime().getTime()), cal); } else { ps.setObject(paramIndex, inValue, Types.DATE); } } else if (sqlType == Types.TIME) { if (inValue instanceof java.util.Date) { if (inValue instanceof java.sql.Time) { ps.setTime(paramIndex, (java.sql.Time) inValue); } else { ps.setTime(paramIndex, new java.sql.Time(((java.util.Date) inValue).getTime())); } } else if (inValue instanceof Calendar) { Calendar cal = (Calendar) inValue; ps.setTime(paramIndex, new java.sql.Time(cal.getTime().getTime()), cal); } else { ps.setObject(paramIndex, inValue, Types.TIME); } } else if (sqlType == Types.TIMESTAMP) { if (inValue instanceof java.util.Date) { if (inValue instanceof java.sql.Timestamp) { ps.setTimestamp(paramIndex, (java.sql.Timestamp) inValue); } else { ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime())); } } else if (inValue instanceof Calendar) { Calendar cal = (Calendar) inValue; ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal); } else { ps.setObject(paramIndex, inValue, Types.TIMESTAMP); } } else if (sqlType == SqlTypeValue.TYPE_UNKNOWN || (sqlType == Types.OTHER && "Oracle".equals(ps.getConnection().getMetaData().getDatabaseProductName()))) { if (isStringValue(inValue.getClass())) { ps.setString(paramIndex, inValue.toString()); } else if (isDateValue(inValue.getClass())) { ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime())); } else if (inValue instanceof Calendar) { Calendar cal = (Calendar) inValue; ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal); } else { // Fall back to generic setObject call without SQL type specified. ps.setObject(paramIndex, inValue); } } else { // Fall back to generic setObject call with SQL type specified. ps.setObject(paramIndex, inValue, sqlType); } }
From source file:org.apache.phoenix.end2end.DateTimeIT.java
@Test public void testNowFunction() throws Exception { String tableName = generateUniqueName(); Date date = new Date(System.currentTimeMillis()); String ddl = "CREATE TABLE IF NOT EXISTS " + tableName + " (k1 INTEGER NOT NULL, timestamps TIMESTAMP CONSTRAINT pk PRIMARY KEY (k1))"; conn.createStatement().execute(ddl); String dml = "UPSERT INTO " + tableName + " VALUES (?, ?)"; PreparedStatement stmt = conn.prepareStatement(dml); stmt.setInt(1, 1);//w w w.j av a 2s. com stmt.setDate(2, new Date(date.getTime() - 500)); stmt.execute(); stmt.setInt(1, 2); stmt.setDate(2, new Date(date.getTime() + 600000)); stmt.execute(); conn.commit(); ResultSet rs = conn.createStatement() .executeQuery("SELECT * from " + tableName + " where now() > timestamps"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals(new Date(date.getTime() - 500), rs.getDate(2)); assertFalse(rs.next()); }