Dificudade ao Puxar dados do banco para Combobox

3 respostas
L

Estou Trabalhando em um projeto onde , tenho q puxar dados do banco para combobox , O projeto nao apresenta erros , mas o campo da combobox fika em branco na pagina da internet . Gostaria de Sabe se a maior possibilidade de esta o erro e na classe converter , ou no Dao . pois na classe d conexão do banco esta tudo certo . mas tarde postarei os Codigo , desde ja Muito Obrigado pela Atenção !!!

3 Respostas

denis_gariglio

Vamos la, o que vc esta utilizando(JSF … Struts).
Esse combobox é nativo ou esta utilizando algum componente(tipo Primefaces)?
Mande mais informações para poder ajudar vc.

[]s

L
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
[b] */
package br.com.delta.dao;[/b]

import br.com.delta.modelo.Curso;
import br.com.delta.util.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CursoDao {
     private Connection conn;

    public CursoDao() throws Exception {
        try {
            this.conn = ConnectionFactory.getConnection();
        } catch (Exception e) {
            throw new Exception("Erro: "
                    + "\n" + e.getMessage());
        }
    }

    public List todosCursos() throws Exception {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = this.conn.prepareStatement("select * from cursos");
            rs = ps.executeQuery();
            List<Curso> list = new ArrayList<Curso>();
            while (rs.next()) {
                Integer id = rs.getInt(1);
                String nome = rs.getString(2);
                list.add(new Curso(id, nome) );
            }
            return list;
        } catch (SQLException sqle) {
            throw new Exception(sqle);
        } finally {
            ConnectionFactory.closeConnection(this.conn, ps, rs);
        }
    }

    public Curso procurarCurso(Integer id)
            throws Exception {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
    ps = this.conn.prepareStatement("select * from Cursos "
            + "where id_cursos=?");
            ps.setInt(1, id);
            rs = ps.executeQuery();
            if (!rs.next()) {
                throw new Exception("Não foi encontrado nenhum"
                        + " registro com o ID: " + id);
            }
            String descricao = rs.getString(2);
            return new Curso(id, descricao);
        } catch (SQLException sqle) {
            throw new Exception(sqle);
        } finally {
            ConnectionFactory.closeConnection(this.conn, ps, rs);

        }
    }


}






/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
[b]package br.com.delta.converter;[/b]

import br.com.delta.dao.CursoDao;
import br.com.delta.modelo.Curso;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;



  @FacesConverter(value = "CursoConverter")
public class CursoConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context,
            UIComponent component, String value) {
        try {
            Curso objCurso =
                    ((Curso) new CursoDao().procurarCurso(Integer.valueOf(value)));
            return objCurso;

        } catch (Exception e) {
            return null;
        }
    }
    @Override
    public String getAsString(FacesContext context,
            UIComponent component,
            Object value) {
        try {
            if (!(value == null)) {
                return String.valueOf(((Curso) value).getId());
            }
        } catch (Exception e) {
        }
        return null;
    }
}

A CIMA TEMOS DUAS CLASES , A CONVERTER , E A DAO , D CONEXAO AO BANCO INFELISMENTE ELE NÃO PUXA OS DADOS DO BANCO !!

denis_gariglio

Suponto que esteja utilizando jsf ... vou mandar um exemplo com primefaces.

populando um treelist

public TreeMap<String,String> lstUm() {

		Conexao conexao;
		TreeMap<String,String> lstUm = new TreeMap<String, String>();
		String sql = "";
		
		sql = "select id_um, desc_um from unidademedida";
		
		try {

			conexao = Conexao.getInstance();
			PreparedStatement stm = conexao.getConexao().prepareStatement(sql);
			ResultSet res = stm.executeQuery();

			while (res.next()) {

				lstUm.put(res.getString("desc_um"), String.valueOf(res.getInt("id_um")));

			}

			stm.close();
			res.close();
			
		} catch (SQLException e) {

			e.printStackTrace();

		} catch (Exception e) {

			e.printStackTrace();

		}

		return lstUm;
	}

meu xhtml

<h:outputLabel for="unidadeMedi" value="Unidade de Medida:" />
					<p:selectOneMenu id="unidadeMedi"
						value="#{produtoBean.unidadeMedi}" required="true"
						requiredMessage="Campo Cidade é obrigatório" >
						<f:selectItem itemLabel="Selecione uma unidade" itemValue="" />
						<f:selectItems value="#{produtoBean.lstum}" />
					</p:selectOneMenu>
					<p:message for="unidadeMedi" display="icon" />

Se isso nao ajuda mande tb o codigo de sua tela.

[]s

Criado 1 de março de 2013
Ultima resposta 4 de mar. de 2013
Respostas 3
Participantes 2