How do I show the data that a Database contains in a JTable?

0

I want to make the Jtable display the data I have in my database. I use a method to connect the database

$ public void Conectar() {      
    try {

        conexion = DriverManager.getConnection("jdbc:mysql://localhost/sistema_gmg", "root", "1405");

        st = conexion.createStatement();        
        rs = st.executeQuery("Select * from ciclos");        
        rs.next();


        this.jtf_id_ciclo.setText(rs.getString("id_ciclo"));

        this.jtf_ciclo.setText(rs.getString("ciclo"));

        this.jtf_finicio.setText(rs.getString("fecha_inicio"));

        this.jtf_ftermino.setText(rs.getString("fecha_termino"));

    } catch (SQLException err) {

        JOptionPane.showMessageDialog(null, "Error " + err.getMessage());

    }
}
    
asked by Miguel Angel 12.07.2017 в 02:19
source

1 answer

0

You have to bring the data from your database as objects, for example in this method the "owners" of a bd are brought and stored in a list, then you can add them to a jtable.

public Propietario[] getPropietarios() {
    int registros = 0;
    try {
        PreparedStatement pstm = cn.getConexion().prepareStatement(
                "SELECT count(1) as cont" + " FROM propietario ");
        ResultSet res = pstm.executeQuery();
        res.next();
        registros = res.getInt("cont");
        res.close();
    } catch (SQLException e) {
        System.out.println(e);
    }
    Propietario[] propietarios = new Propietario[registros];
    try {
        PreparedStatement pstm = cn.getConexion().prepareStatement(
                "SELECT id_propietario, nombre, apellido, celular "+ " FROM propietario "
        );
        ResultSet res = pstm.executeQuery();
        int i = 0;
        while (res.next()) {
            propietarios[i] = new Propietario();
            propietarios[i].setIdPropietario(res.getInt("id_propietario"));
            propietarios[i].setNombre(res.getString("nombre"));
            propietarios[i].setApellido(res.getString("apellido"));
            propietarios[i].setCelular(res.getString("celular"));
            i++;
        }
        res.close();
    } catch (SQLException e) {
        System.out.println(e);
    }
    return propietarios;
}
    
answered by 12.07.2017 / 03:51
source