List of usage examples for java.sql PreparedStatement setFloat
void setFloat(int parameterIndex, float x) throws SQLException;
float
value. 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 ww w . j ava2 s . c om 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//from w w w . ja v a2s.c o m * @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.brucalipto.sqlutil.SQLManager.java
/** * Method useful for SQL SELECT/*from w ww. ja va2 s . c o m*/ * @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:Logica.Usuario.java
/** * * @param cinterno/*from w w w . j a v a2s. c o m*/ * @param cantidad * @return * @throws RemoteException * * Actualiza la cantidad de un tem en particular. */ @Override public boolean updateCantidad(String cinterno, float cantidad) throws RemoteException { EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU"); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String statement = "update item set cantidad = cantidad +? where CINTERNO =?"; boolean updated = false; try { con = Conexion.conexion.getConnection(); ps = con.prepareStatement(statement); ps.setFloat(1, cantidad); ps.setString(2, cinterno); ps.executeUpdate(); updated = true; } catch (SQLException ex) { Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ps != null) { ps.close(); } if (rs != null) { rs.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.out.println("Error cerrando conexion"); } } return updated; }
From source file:org.tec.webapp.jdbc.entity.support.PreparedStatementBuilder.java
/** * Set a prepared statement field based on type * * @param stmt PrepapredStatement/* w w w. j av a2s . c o m*/ * @param index index of the parameter in the stmt * @param param the param value and metadata */ protected void setParameter(PreparedStatement stmt, int index, Parameter param) { try { if (param.getData() == null) { stmt.setNull(index, param.getType().getVendorTypeNumber()); } else { switch (param.getType()) { case BOOLEAN: stmt.setBoolean(index, (Boolean) param.getData()); break; case DATE: /* * java.sql.Date date = TextHelper.parseDate(param.getData()); if * (null == date) { throw new * SQLException("failed to set parameter: stmt=" + stmt + " index=" * + index + " param=" + param); } stmt.setDate(index, date); */ break; case TIME: /* * Time time = TextHelper.parseTime(param.getData()); if (null == * time) { throw new SQLException("failed to set parameter: stmt=" + * stmt + " index=" + index + " param=" + param); } * stmt.setTime(index, time); */ break; case TIMESTAMP: /* * Timestamp ts = TextHelper.parseTimestamp(param.getData()); if * (null == ts) { throw new * SQLException("failed to set parameter: stmt=" + stmt + " index=" * + index + " param=" + param); } stmt.setTimestamp(index, ts); */ break; case INTEGER: if (param.getData() instanceof Long) { Long l = (Long) param.getData(); stmt.setLong(index, l); } else { Integer i = (Integer) param.getData(); stmt.setInt(index, i); } break; case FLOAT: Float f = (Float) param.getData(); stmt.setFloat(index, f); break; default: // set string for non explicit types String tmp = StringUtils.replaceEachRepeatedly((String) param.getData(), INVALID_TEXT_CHARS, CORRECT_TEXT_CHARS); stmt.setString(index, tmp); break; } } } catch (Throwable e) { throw new RuntimeException("failed to process parameter " + param, e); } }
From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java
/** * @param pStmt//from www .ja v a 2s . c o m * @param type * @param data * @throws SQLException */ public static void setData(final PreparedStatement pStmt, final int type, final int colInx, final Object data) throws SQLException { if (data == null) { pStmt.setObject(colInx, null); return; } boolean isStr = data instanceof String; switch (type) { case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: case java.sql.Types.INTEGER: if (isStr) { pStmt.setString(colInx, (String) data); } else { pStmt.setInt(colInx, (Integer) data); } break; case java.sql.Types.FLOAT: if (isStr) { pStmt.setString(colInx, (String) data); } else { pStmt.setFloat(colInx, (Float) data); } break; case java.sql.Types.VARCHAR: case java.sql.Types.CHAR: case java.sql.Types.LONGVARCHAR: case java.sql.Types.LONGNVARCHAR: case java.sql.Types.NCHAR: if (isStr) { pStmt.setString(colInx, (String) data); } else { pStmt.setString(colInx, (String) data); } break; case java.sql.Types.REAL: case java.sql.Types.DOUBLE: if (isStr) { pStmt.setString(colInx, (String) data); } else { pStmt.setDouble(colInx, (Double) data); } break; case java.sql.Types.DATE: if (isStr) { pStmt.setString(colInx, (String) data); } else { pStmt.setDate(colInx, (java.sql.Date) data); } break; case java.sql.Types.TIMESTAMP: if (isStr) { pStmt.setString(colInx, (String) data); } else { pStmt.setTimestamp(colInx, (Timestamp) data); } break; case java.sql.Types.BOOLEAN: if (isStr) { String val = (String) data; pStmt.setBoolean(colInx, !val.equalsIgnoreCase("true")); } else { pStmt.setBoolean(colInx, (Boolean) data); } break; case java.sql.Types.BIT: if (data instanceof Boolean) { pStmt.setBoolean(colInx, (Boolean) data); } else { pStmt.setBoolean(colInx, !(((Integer) data) == 0)); } break; default: throw new RuntimeException(String.format("Missing case for SQL Type %d for Column: %d Data[%s]", type, colInx, data.getClass().getSimpleName())); } }
From source file:migration.ProjektMigration.java
/** * Creates the journalkosten./*from ww w.ja v a 2 s . c om*/ */ public void createJournalkosten() { String load_sql; Statement load_stmt; ResultSet load_rs; String store_sql; PreparedStatement store_prepstmt; final ResultSet store_rs; try { load_sql = "SELECT IMwStO, IMwStP, IMwStPO, IPreisO, IPreisP, IPreisPO, IWaehrungO, IWaehrungP, IWaehrungPO, OPreisO, OPreisP, OPreisPO, Impact, ImpactDatum, MwStO, MwStP, MwStPO, WaehrungO, WaehrungP, WaehrungPO, Titelnummer FROM ZSTiteltabelle"; load_stmt = this.leg_con.createStatement(); store_sql = "INSERT INTO Journalkosten (IMwStO, IMwStP, IMwStPO, IPreisO, IPreisP, IPreisPO, IWaehrungO, IWaehrungP, IWaehrungPO, OPreisO, OPreisP, OPreisPO, impact, impactDatum, mwStO, mwStP, mwStPO, waehrungO, waehrungP, waehrungPO, journal_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; store_prepstmt = this.tgt_con.prepareStatement(store_sql); // evtl. // brauchen // wir // was // in // Richtung: // Statement.RETURN_GENERATED_KEYS // logger.info("Lese von ZSTiteltabelle (Journalkosten)"); load_stmt.execute(load_sql); load_rs = load_stmt.getResultSet(); // logger.info("Schreibe nach Journalkosten"); while (load_rs.next()) { final int titelnummer = load_rs.getInt("Titelnummer"); final int journalID = this.help.getIdFromIntArray(this.help.getJournals(), titelnummer); // ystem.out.println("Titelnummer: " + titelnummer + // " JournalID " + journalID); if ((titelnummer > 0) && (journalID > 0)) { store_prepstmt.setString(1, load_rs.getString("IMwStO")); store_prepstmt.setString(2, load_rs.getString("IMwStP")); store_prepstmt.setString(3, load_rs.getString("IMwStPO")); store_prepstmt.setFloat(4, load_rs.getFloat("IPreisO")); store_prepstmt.setFloat(5, load_rs.getFloat("IPreisP")); store_prepstmt.setFloat(6, load_rs.getFloat("IPreisPO")); store_prepstmt.setString(7, load_rs.getString("IWaehrungO")); store_prepstmt.setString(8, load_rs.getString("IWaehrungP")); store_prepstmt.setString(9, load_rs.getString("IWaehrungPO")); store_prepstmt.setFloat(10, load_rs.getFloat("OPreisO")); store_prepstmt.setFloat(11, load_rs.getFloat("OPreisP")); store_prepstmt.setFloat(12, load_rs.getFloat("OPreisPO")); store_prepstmt.setFloat(13, load_rs.getFloat("Impact")); store_prepstmt.setDate(14, load_rs.getDate("ImpactDatum")); store_prepstmt.setString(15, load_rs.getString("MwStO")); store_prepstmt.setString(16, load_rs.getString("MwStP")); store_prepstmt.setString(17, load_rs.getString("MwStPO")); store_prepstmt.setString(18, load_rs.getString("WaehrungO")); store_prepstmt.setString(19, load_rs.getString("WaehrungP")); store_prepstmt.setString(20, load_rs.getString("WaehrungPO")); store_prepstmt.setLong(21, journalID); store_prepstmt.executeUpdate(); } } } catch (final SQLException e) { e.printStackTrace(); // To change body of catch statement use File | // Settings | File Templates. } }
From source file:Logica.Usuario.java
/** * * @param d/*ww w. j a va 2s. c om*/ * @return * @throws RemoteException * * Registra el descargo de un tem en la base de datos. */ @Override public boolean realizarDescargo(descargo d) throws RemoteException { EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU"); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String statement = "INSERT INTO DESCARGO(FECHA, ID_usuario, AREA, CANTIDAD, CINTERNO) VALUES (?,?,?,?,?)"; boolean valido = false; try { con = Conexion.conexion.getConnection(); ps = con.prepareStatement(statement); ps.setDate(1, new Date(d.getFecha().getTimeInMillis())); ps.setString(2, d.getId()); ps.setString(3, d.getArea()); ps.setFloat(4, d.getCantidad()); ps.setString(5, d.getCinterno()); ps.executeUpdate(); this.updateCantidad(d.getCinterno(), d.getCantidad() * -1); valido = true; } catch (SQLException ex) { Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ps != null) { ps.close(); } if (rs != null) { rs.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.out.println("Error cerrando conexion"); } } return valido; }
From source file:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java
private void setRealValue(int queryType, String value, String paramType, PreparedStatement sqlQuery, int i) throws SQLException { Float val = null; if (value != null) { val = new Float(value); }/*from ww w .j ava2s. co m*/ if (QueryTypes.IN.equals(paramType)) { if (queryType == SQLQuery.DS_QUERY_TYPE_NORMAL) { if (value == null) { sqlQuery.setNull(i + 1, java.sql.Types.FLOAT); } else { sqlQuery.setFloat(i + 1, val); } } else { if (value == null) { ((CallableStatement) sqlQuery).setNull(i + 1, java.sql.Types.FLOAT); } else { ((CallableStatement) sqlQuery).setFloat(i + 1, val); } } } else if (QueryTypes.INOUT.equals(paramType)) { if (value == null) { ((CallableStatement) sqlQuery).setNull(i + 1, java.sql.Types.FLOAT); } else { ((CallableStatement) sqlQuery).setFloat(i + 1, val); } ((CallableStatement) sqlQuery).registerOutParameter(i + 1, java.sql.Types.FLOAT); } else { ((CallableStatement) sqlQuery).registerOutParameter(i + 1, java.sql.Types.FLOAT); } }
From source file:org.etudes.component.app.jforum.JforumDataServiceImpl.java
private int createGrade(Connection connection, String toContextId, int gradeType, int forumId, int topicId, int categoryId, float gradePoints, int addToGradebook, boolean minPostsRequired, int minPosts, String gradebookTitle) throws SQLException { int gradeId = -1; ResultSet rs = null;//from www . ja v a 2 s. co m String gradebookToolId = ServerConfigurationService.getString(JForumGradeService.GRADEBOOK_TOOL_ID); if ((gradebookToolId == null) || (gradebookToolId.trim().length() == 0)) { gradebookToolId = "sakai.gradebook.tool"; } Site site = null; try { site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); } catch (IdUnusedException e) { if (logger.isWarnEnabled()) { logger.warn(e.toString(), e); } } boolean gradebookExists = false; if ((site != null) && (site.getToolForCommonId(gradebookToolId) != null)) { gradebookExists = true; } if (sqlService.getVendor().equals("oracle")) { String gradeModelAddNewsql = "INSERT INTO jforum_grade(grade_id, context, grade_type, forum_id, topic_id, categories_id, points, add_to_gradebook, min_posts_required, min_posts) " + "VALUES (jforum_grade_seq.nextval, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement p = connection.prepareStatement(gradeModelAddNewsql); p.setString(1, toContextId); p.setInt(2, gradeType); p.setInt(3, forumId); p.setInt(4, topicId); p.setInt(5, categoryId); p.setFloat(6, gradePoints); if (gradebookExists) { String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); JForumGBService jForumGBService = null; jForumGBService = (JForumGBService) ComponentManager .get("org.etudes.api.app.jforum.JForumGBService"); if (!jForumGBService.isAssignmentDefined(gradebookUid, gradebookTitle)) { p.setInt(7, addToGradebook); } else { addToGradebook = 0; p.setInt(7, 0); } } else { p.setInt(7, 0); } if (minPostsRequired) { p.setInt(8, 1); p.setInt(9, minPosts); } else { p.setInt(8, 0); p.setInt(9, 0); } p.executeUpdate(); p.close(); String gradeLastGeneratedGradeId = "SELECT jforum_grade_seq.currval FROM DUAL"; p = connection.prepareStatement(gradeLastGeneratedGradeId); rs = p.executeQuery(); if (rs.next()) { gradeId = rs.getInt(1); } rs.close(); p.close(); } else if (sqlService.getVendor().equalsIgnoreCase("mysql")) { String gradeModelAddNewsql = "INSERT INTO jforum_grade(context, grade_type, forum_id, topic_id, categories_id, points, add_to_gradebook, min_posts_required, min_posts) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement p = connection.prepareStatement(gradeModelAddNewsql, Statement.RETURN_GENERATED_KEYS); p.setString(1, toContextId); p.setInt(2, gradeType); p.setInt(3, forumId); p.setInt(4, topicId); p.setInt(5, categoryId); p.setFloat(6, gradePoints); if (gradebookExists) { String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); JForumGBService jForumGBService = null; jForumGBService = (JForumGBService) ComponentManager .get("org.etudes.api.app.jforum.JForumGBService"); if (!jForumGBService.isAssignmentDefined(gradebookUid, gradebookTitle)) { p.setInt(7, addToGradebook); } else { addToGradebook = 0; p.setInt(7, 0); } } else { p.setInt(7, 0); } if (minPostsRequired) { p.setInt(8, 1); p.setInt(9, minPosts); } else { p.setInt(8, 0); p.setInt(9, 0); } p.executeUpdate(); rs = p.getGeneratedKeys(); if (rs.next()) { gradeId = rs.getInt(1); } rs.close(); p.close(); } return gradeId; }