Java Code Examples for java.sql.PreparedStatement.setDouble()

The following are Jave code examples for showing how to use setDouble() of the java.sql.PreparedStatement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: tcp   File: SqlInserts.java   Source Code and License Vote up 6 votes
public static boolean insertAvanceCosto(AvanceCosto costo, String usuarioResponsable){
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into avance_costo (monto,codigo_contratacionl,objeto_gasto,avance_id, producto_concat, usuario_responsable)"
	+ " values (?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		
		
		insert.setDouble (1, costo.getMonto());
		insert.setString (2, costo.getCodigoContratacion());
		insert.setInt (3, costo.getObjetoGasto());
		insert.setInt (4, costo.getAvanceId());
		insert.setString(5, costo.getProductoConcat());
		insert.setString (6, usuarioResponsable);
		
		insert.execute();
		   
		conn.close();
		return true;
	} catch (SQLException e) {e.printStackTrace(); return false;}
	
}
 
Example 2
Project: LojaDeInstrumentosMusicais   File: ProdutoDAO.java   Source Code and License Vote up 6 votes
public void inserirProduto(Produto produto){
    System.out.println("Iniciando processo de inserção de produto...");
    String query = "insert into produtos (codigoempresa, nome, descricao, codigofornecedor, codigocategoria, precocompra, precovenda, estoque) values (?,?,?,?,?,?,?,?)";
    
    try {
        PreparedStatement preparedStatement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        
        preparedStatement.setInt(1, produto.getCodigoempresa());
        preparedStatement.setString(2, produto.getNome());
        preparedStatement.setString(3, produto.getDescricao());
        preparedStatement.setInt(4, produto.getCodigoFornecedor());
        preparedStatement.setInt(5, produto.getCategoria());
        preparedStatement.setDouble(6, produto.getPrecocompra());
        preparedStatement.setDouble(7, produto.getPrecovenda());
        preparedStatement.setInt(8, produto.getEstoque());
        
        preparedStatement.executeUpdate();
        preparedStatement.close();
        System.out.println("Produto inserido com sucesso.");
        
    } catch (SQLException ex) {
        System.out.println(ex);
        System.out.println("Erro ao salvar produto");
    }
}
 
Example 3
Project: open-rmbt   File: QueryParser.java   Source Code and License Vote up 6 votes
/**
 * Fills in the given fields in the queue into the given prepared statement
 * @param ps
 * @param firstField
 * @return
 * @throws SQLException
 */
public int fillInWhereClause(PreparedStatement ps, int firstField) throws SQLException{
	//insert all values in the prepared statement in the order
    //in which the values had been put in the queue
    for (Map.Entry<String, FieldType> entry : searchValues){
        switch(entry.getValue()) {
            case STRING:
                ps.setString(firstField, entry.getKey());
                break;
            case DATE:
                ps.setTimestamp(firstField, new Timestamp(Long.parseLong(entry.getKey())));
                break;
            case LONG:
                ps.setLong(firstField, Long.parseLong(entry.getKey()));
                break;
            case DOUBLE:
                ps.setDouble(firstField, Double.parseDouble(entry.getKey()));
                break;
            case UUID:
                ps.setObject(firstField, UUID.fromString(entry.getKey()));
                break;
            case BOOLEAN:
            	ps.setBoolean(firstField, Boolean.valueOf(entry.getKey()));
            	break;
        }
        firstField++;
    }
    return firstField;
}
 
Example 4
Project: spr   File: SqlInserts.java   Source Code and License Vote up 6 votes
public static void insertEstructuraFinanciera(EstructuraFinanciera estructuraFinanciera, String usuarioResponsable){
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into estructura_financiera (id,estructura,mes,producto,ejecutado,programado,usuario_responsable)"
		+ " values (?, ?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		
		insert.setInt (1, estructuraFinanciera.getId());
		insert.setInt (2, estructuraFinanciera.getEstructura());
		insert.setInt (3, estructuraFinanciera.getMes());
		insert.setInt (4, estructuraFinanciera.getProducto());
		insert.setDouble (5, estructuraFinanciera.getEjecutado());
		insert.setDouble (6, estructuraFinanciera.getPlanificado());
		insert.setString (7, usuarioResponsable);
							
		insert.execute();
		   
		conn.close();
	} catch (SQLException e) {e.printStackTrace();}
		
}
 
Example 5
Project: spr   File: SqlHelper.java   Source Code and License Vote up 6 votes
public static void insertProyectoSnipAutorizado(int id, int proyecto_snip_id, int anho, int entidad_nivel_id, int entidad_id, int fuente_financiamiento_id, int	organisimo_financiador_id, Double monto){
 	 Connection conect=conectar();
 String query = " insert into proyecto_snip_autorizado ( id, proyecto_snip_id, anho, entidad_nivel_id, entidad_id, fuente_financiamiento_id, organisimo_financiador_id, monto)"
	        + " values (?,?,?,?,?,?,?,?)";
try {
	
	PreparedStatement preparedStmt;
	preparedStmt = conect.prepareStatement(query);
	preparedStmt.setInt (1, id);
	preparedStmt.setInt (2, proyecto_snip_id);
	preparedStmt.setInt (3, anho);
	preparedStmt.setInt (4, entidad_nivel_id);
	preparedStmt.setInt (5, entidad_id);
	preparedStmt.setInt (6, fuente_financiamiento_id);
	preparedStmt.setInt (7, organisimo_financiador_id);
	preparedStmt.setDouble(8, monto);
    preparedStmt.execute();
    conect.close();
} catch (SQLException e) {e.printStackTrace();}
 }
 
Example 6
Project: S3-16-d-rescue   File: RescueTeamDaoImpl.java   Source Code and License Vote up 6 votes
@Override
protected PreparedStatement fillStatement(final ObjectModel objectModel, final PreparedStatement statement, final QueryType queryType) throws SQLException {
    final RescueTeam rescueTeam = ((RescueTeam) objectModel);
    switch (queryType) {
        case INSERT:
            statement.setString(1, rescueTeam.getRescueTeamID());
            statement.setString(2, rescueTeam.getPassword());
            statement.setString(3, rescueTeam.getName());
            statement.setDouble(4, rescueTeam.getLatitude());
            statement.setDouble(5, rescueTeam.getLongitude());
            statement.setString(6, rescueTeam.getPhoneNumber());
            break;
        case FIND_ONE:
        case DELETE:
            statement.setString(1, rescueTeam.getRescueTeamID());
            break;
        case UPDATE:
            statement.setString(1, rescueTeam.getPassword());
            statement.setString(2, rescueTeam.getRescueTeamID());
            break;
        default:
            throw new SQLException(QUERY_NOT_FOUND_EXCEPTION);
    }
    return statement;
}
 
Example 7
Project: Java-9-Cookbook   File: DbUtil.java   Source Code and License Vote up 5 votes
public static void recordData(Connection conn, TrafficUnit tu, double speed) {
        String sql = "insert into data(vehicle_type, horse_power, weight_pounds, passengers_count, payload_pounds, speed_limit_mph, " +
                "temperature, road_condition, tire_condition, traction, speed) values(?,?,?,?,?,?,?,?,?,?,?)";
/*
        System.out.println("  " + sql + ", params=" + tu.getVehicleType() + ", " + tu.getHorsePower() + ", " + tu.getWeightPounds()
                + ", " + tu.getPassengersCount() + ", " + tu.getPayloadPounds() + ", " + tu.getSpeedLimitMph() + ", " + tu.getTemperature()
                + ", " + tu.getRoadCondition() + ", " + tu.getTireCondition()+ ", " + tu.getTraction() + ", " + speed);
*/
        try {
            int i = 1;
            PreparedStatement st = conn.prepareStatement(sql);
            st.setString(i++, tu.getVehicleType().name());
            st.setInt(i++, tu.getHorsePower());
            st.setInt(i++, tu.getWeightPounds());
            st.setInt(i++, tu.getPassengersCount());
            st.setInt(i++, tu.getPayloadPounds());
            st.setDouble(i++, tu.getSpeedLimitMph());
            st.setInt(i++, tu.getTemperature());
            st.setString(i++, tu.getRoadCondition().name());
            st.setString(i++, tu.getTireCondition().name());
            st.setDouble(i++, tu.getTraction());
            st.setDouble(i++, speed);
            int count = st.executeUpdate();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
 
Example 8
Project: zencash-swing-wallet-ui   File: ArizenWallet.java   Source Code and License Vote up 5 votes
@Override
public void insertAddress(Address address) throws Exception {		
		String sql = address.getType() == Address.ADDRESS_TYPE.TRANSPARENT ? sqlInsertPublicAddress : sqlInsertPrivateAddress;					
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, address.getPrivateKey());
        pstmt.setString(2, address.getAddress());
        pstmt.setDouble(3, Double.parseDouble(address.getBalance()));
        pstmt.setString(4, "");
		pstmt.execute();
}
 
Example 9
Project: tcp   File: SqlInserts.java   Source Code and License Vote up 5 votes
public static boolean insertAvance(Avance avance, String usuarioResponsable) throws ParseException{
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into avance (departamento_id, distrito_avance, justificacion,cantidad,fecha_entrega,actividad_id,version, usuario_responsable)"
	+ " values (?, ?, ?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		
		String inicio = avance.getFechaEntrega();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		java.util.Date date1 = sdf.parse(inicio);
		java.sql.Date sqlStart = new java.sql.Date(date1.getTime());
		
		insert.setInt (1, avance.getDepartamentoId());
		insert.setInt (2, avance.getDistritoAvance());
		insert.setString (3, avance.getJustificacion());
		insert.setDouble(4, avance.getCantidad());
		insert.setDate (5, sqlStart); 
		insert.setInt (6, avance.getActividadId());
		insert.setInt (7, avance.getVersion());
		insert.setString (8, usuarioResponsable);
		
		insert.execute();
		   
		conn.close();
		return true;
	} catch (SQLException e) {e.printStackTrace(); return false;}
	
}
 
Example 10
Project: spr   File: SqlInserts.java   Source Code and License Vote up 5 votes
public static void insertFundamentacion(Fundamentacion fundamentacion, String usuarioResponsable){
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into fundamentacion (id, estructura_id, objeto_gasto, fuente_financiamiento, org_financiador, pais, depto, secuencia, precio, cantidad, cantidad_meses, descripcion, clgCodigo, usuarioResponsable)"
		+ " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		
		insert.setInt (1, fundamentacion.getId());
		insert.setInt (2, fundamentacion.getEstructura());
		insert.setInt (3, fundamentacion.getObjetoGasto());
		insert.setInt (4, fundamentacion.getFuenteFinanciamiento());
		insert.setInt (5, fundamentacion.getOrganismoFinanciador());
		insert.setInt (6, fundamentacion.getPais());
		insert.setInt (7, fundamentacion.getDepto());
		insert.setInt (8, fundamentacion.getSecuencia());
		insert.setDouble (9, fundamentacion.getPrecio());
		insert.setInt (10, fundamentacion.getCantidad());
		insert.setInt (11, fundamentacion.getCantidad_meses());
		insert.setString (12, fundamentacion.getDescripcion());
		insert.setInt (13, fundamentacion.getClgCodigo());
		insert.setString (14, usuarioResponsable);	
							
		insert.execute();
		   
		conn.close();
	} catch (SQLException e) {e.printStackTrace();}
		
}
 
Example 11
Project: LogisticApp   File: RotaDAOSQL.java   Source Code and License Vote up 5 votes
@Override
public void update(Rota rota) throws Exception {
	PreparedStatement pstm = this.getConnectionFactory().getConnection()
			.prepareStatement(RotaQueries.UPDATE_ROTA.getConsulta());
	pstm.setInt(1, rota.getId());
	pstm.setString(2, rota.getNome());
	pstm.setObject(3, (rota.getOrigem() == null) ? null : rota.getOrigem().getId());
	pstm.setObject(4, (rota.getDestino() == null) ? null : rota.getDestino().getId());
	pstm.setDouble(7, rota.getCustoGrama());
	pstm.setInt(8, rota.getTempoEntrega());
	pstm.setInt(10, rota.getId());
	if (rota instanceof Direta) {
		Direta direta = (Direta) rota;
		pstm.setDouble(5, direta.getCapacidadeTotal());
		pstm.setDouble(6, direta.getCapacidadeAlocada());
		pstm.setString(9, "D");
	} else if (rota instanceof Fracional) {
		pstm.setObject(5, null);
		pstm.setObject(6, null);
		pstm.setString(9, "F");
	}
	try {
		pstm.executeUpdate();
		if (rota instanceof Fracional)
			this.updateTrechos((Fracional) rota);
	} catch (Exception ex) {
		throw new LogisticException("Erro durante a rotina de atualização de rotas.");
	}
}
 
Example 12
Project: dev-courses   File: TestBatchBug.java   Source Code and License Vote up 5 votes
static void populateTable(Connection con) throws SQLException {

        long      startTime = System.currentTimeMillis();
        Timestamp now       = new Timestamp(startTime);

        con.setAutoCommit(false);

        String            sql  = createInsertSQL(true, false);
        PreparedStatement prep = con.prepareStatement(sql);

        prep.clearParameters();
        prep.setString(1, "xxx");
        prep.setTimestamp(2, now);    // last_update

        for (int ii = 0; ii < DECIMAL_FIELDS_PER_DATASET; ii++) {
            prep.setDouble(ii + 3, 0.123456789);    // Wert
        }

        prep.addBatch();
        prep.setString(1, "yyy");
        prep.setTimestamp(2, now);    // last_update

        for (int ii = 0; ii < DECIMAL_FIELDS_PER_DATASET; ii++) {
            prep.setDouble(ii + 3, 0.123456789);    // Wert
        }

        prep.addBatch();

        int[] updateCounts = prep.executeBatch();

        con.setAutoCommit(true);
        prep.close();
    }
 
Example 13
Project: tcp   File: SqlInserts.java   Source Code and License Vote up 5 votes
public static void insertActividad(Cronograma actividad, String usuarioResponsable){
	try {
		Connection conn=ConnectionConfiguration.conectar();
	   	
		String query = " insert into actividad (nombre,descripcion,proporcion,peso,version,borrado,accion_id,unidad_medida_id,hito_tipo_id,acumulable, usuario_responsable, prod_concat)"
	+ " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		
		insert.setString (1, actividad.getNombre());
		insert.setString (2, actividad.getDescripcion());
		insert.setDouble (3, actividad.getProporcion());
		insert.setDouble (4, actividad.getPeso());
		insert.setInt (5, actividad.getVersion());
		insert.setBoolean (6, actividad.isBorrado());
		insert.setInt (7, actividad.getAccion_id());
		insert.setInt (8, actividad.getUnidad_medida_id());
		insert.setInt (9, actividad.getHito_tipo_id());	
		insert.setBoolean(10, actividad.isAcumulable());		
		insert.setString (11, usuarioResponsable);
		insert.setString(12, actividad.getProdConcat());
		
		insert.execute();
		   
		conn.close();
	} catch (SQLException e) {e.printStackTrace();}
	
}
 
Example 14
Project: lams   File: DoubleTypeDescriptor.java   Source Code and License Vote up 5 votes
@Override
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
	return new BasicBinder<X>( javaTypeDescriptor, this ) {
		@Override
		protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
			st.setDouble( index, javaTypeDescriptor.unwrap( value, Double.class, options ) );
		}
	};
}
 
Example 15
Project: LojaDeInstrumentosMusicais   File: CarrinhoDAO.java   Source Code and License Vote up 5 votes
public void alterarValor(double valor) throws Exception{
    String query = "UPDATE carrinho SET valortotal= ?";

    try {
        PreparedStatement preparedStatement = conn.prepareStatement(query);
        preparedStatement.setDouble(1, valor);

        preparedStatement.execute();
        System.out.println("Valor Alterado");
    } catch (SQLException ex) {
        throw new Exception("Erro ao deletar o carrinho", ex);
    
    }
}
 
Example 16
Project: parabuild-ci   File: TestBatchBug.java   Source Code and License Vote up 5 votes
static void populateTable(Connection con) throws SQLException {

        long      startTime = System.currentTimeMillis();
        Timestamp now       = new Timestamp(startTime);

        con.setAutoCommit(false);

        String            sql  = createInsertSQL(true, false);
        PreparedStatement prep = con.prepareStatement(sql);

        prep.clearParameters();
        prep.setString(1, "xxx");
        prep.setTimestamp(2, now);    // last_update

        for (int ii = 0; ii < DECIMAL_FIELDS_PER_DATASET; ii++) {
            prep.setDouble(ii + 3, 0.123456789);    // Wert
        }

        prep.addBatch();
        prep.setString(1, "yyy");
        prep.setTimestamp(2, now);    // last_update

        for (int ii = 0; ii < DECIMAL_FIELDS_PER_DATASET; ii++) {
            prep.setDouble(ii + 3, 0.123456789);    // Wert
        }

        prep.addBatch();

        int[] updateCounts = prep.executeBatch();

        con.setAutoCommit(true);
        prep.close();
    }
 
Example 17
Project: rapidminer   File: DatabaseHandler.java   Source Code and License Vote up 4 votes
public ResultSet executeStatement(String sql, boolean isQuery, Operator parameterHandler, Logger logger) throws SQLException, OperatorException {
    checkDatabaseConstraintOnOperator(parameterHandler, this.databaseURL);
    ResultSet resultSet = null;
    Object statement = null;

    try {
        if(parameterHandler.getParameterAsBoolean("prepare_statement")) {
            PreparedStatement prepared = this.getConnection().prepareStatement(sql);
            String[] parameters = ParameterTypeEnumeration.transformString2Enumeration(parameterHandler.getParameterAsString("parameters"));

            for(int i = 0; i < parameters.length; ++i) {
                String[] argDescription = ParameterTypeTupel.transformString2Tupel(parameters[i]);
                String sqlType = argDescription[0];
                String replacementValue = argDescription[1];
                if("VARCHAR".equals(sqlType)) {
                    prepared.setString(i + 1, replacementValue);
                } else if("REAL".equals(sqlType)) {
                    try {
                        prepared.setDouble(i + 1, Double.parseDouble(replacementValue));
                    } catch (NumberFormatException var21) {
                        prepared.close();
                        throw new UserError(parameterHandler, 158, new Object[]{replacementValue, sqlType});
                    }
                } else if("LONG".equals(sqlType)) {
                    try {
                        prepared.setLong(i + 1, Long.parseLong(replacementValue));
                    } catch (NumberFormatException var20) {
                        prepared.close();
                        throw new UserError(parameterHandler, 158, new Object[]{replacementValue, sqlType});
                    }
                } else {
                    if(!"INTEGER".equals(sqlType)) {
                        prepared.close();
                        throw new OperatorException("Illegal data type: " + sqlType);
                    }

                    try {
                        prepared.setInt(i + 1, Integer.parseInt(replacementValue));
                    } catch (NumberFormatException var19) {
                        prepared.close();
                        throw new UserError(parameterHandler, 158, new Object[]{replacementValue, sqlType});
                    }
                }
            }

            if(isQuery) {
                resultSet = this.executeQuery(prepared, parameterHandler);
            } else {
                this.execute(prepared, parameterHandler);
            }

            statement = prepared;
        } else {
            logger.info("Executing query: \'" + sql + "\'");
            statement = this.createStatement(false);
            if(isQuery) {
                resultSet = this.executeQuery((Statement)statement, parameterHandler, sql);
            } else {
                this.execute((Statement)statement, parameterHandler, sql);
            }
        }
    } finally {
        logger.fine("Query executed.");
        if(!isQuery && statement != null) {
            ((Statement)statement).close();
        }

    }

    return resultSet;
}
 
Example 18
Project: tangyuan2   File: DoubleTypeHandler.java   Source Code and License Vote up 4 votes
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Double parameter, JdbcType jdbcType) throws SQLException {
	ps.setDouble(i, parameter);
}
 
Example 19
Project: tcp   File: SqlUpdates.java   Source Code and License Vote up 4 votes
public static boolean updateHito(Hito objeto, String usuarioResponsable){
 	try {             
		Connection conect=ConnectionConfiguration.conectar();
		String	query = "update hito set ";
		PreparedStatement update =null;

		if(objeto.getNombre()!=null)	      		query+= "nombre= ?";
		if(objeto.getDescripcion()!=null)	    	query+= ", descripcion= ?";
		if(objeto.getCantidad()!=0)					query+= ", cantidad= ?";
		if(objeto.getFechaEntrega()!=null)			query+= ", fecha_entrega= ?";
		if(objeto.getHitoTipoId()!=0)				query+= ", hito_tipo_id= ?";
		if(objeto.getAccionId()!=0)					query+= ", accion_id= ?";
		if(objeto.getEvidenciaId()!=0)				query+= ", evidencia_id= ?";
		if(objeto.getUnidadMedidaId()!=0)			query+= ", unidad_medida_id= ?";
		if(objeto.getPeso()!=0)						query+= ", peso= ?";
													query += ", usuario_responsable = ? ";
			
		query+=" where id = ?";

		int cantCampos =0;
		update = conect.prepareStatement(query);
		if (objeto.getNombre()!=null)  				{    cantCampos++;update.setString (cantCampos, objeto.getNombre());}
		if (objeto.getDescripcion()!=null)	   		{    cantCampos++;update.setString (cantCampos, objeto.getDescripcion());}
		if (objeto.getCantidad()!=0)				{    cantCampos++;update.setDouble (cantCampos, objeto.getCantidad());}
		if (objeto.getFechaEntrega()!=null)			{    cantCampos++;update.setDate(cantCampos, objeto.getFechaEntrega());}
		if (objeto.getHitoTipoId()!=0)				{    cantCampos++;update.setInt (cantCampos, objeto.getHitoTipoId());}
		if (objeto.getAccionId()!=0)				{    cantCampos++;update.setInt (cantCampos, objeto.getAccionId());}
		if (objeto.getEvidenciaId()!=0)				{    cantCampos++;update.setInt (cantCampos, objeto.getEvidenciaId());}
		if (objeto.getUnidadMedidaId()!=0)			{    cantCampos++;update.setInt (cantCampos, objeto.getUnidadMedidaId());}
		if (objeto.getPeso()!=0)					{    cantCampos++;update.setInt (cantCampos, objeto.getPeso());}
			
			cantCampos++;
			update.setString (cantCampos, usuarioResponsable);
		
			cantCampos++;
            update.setInt    (cantCampos , objeto.getId());

            update.execute();
		    conect.close();
		    return true;
	} catch (SQLException e) {e.printStackTrace(); return false;}	
}
 
Example 20
Project: uavstack   File: DAOFactory.java   Source Code and License Vote up 2 votes
public void setParameter(PreparedStatement ps, int i, Object parameter) throws SQLException {

            ps.setDouble(i, ((Double) parameter).doubleValue());
        }