Hilfe bei dem Erstellen einer SQL Abfrage aus gewählten JComboBoxen

Ickenichdu

Mitglied
Hi Leute, im rahmen eines Projektes habe ich eine Oberfläche gebaut mit welcher ich nun aus den ausgewählten JComboBoxen ein query erstellen möchte, dass funktioniert auch soweit. Allerdings funktioniert das nur für alle Auswahlkriterien. Ich würde gerne, dass er bei der ersten Combobox, nur einen ganzen Table auswählt (SELECT * FROM ...), beim der zweiten ComboBox, aus dieser dann eine Bedingung dazuholt (SELECT * FROM ... WHERE ...) und sollte mann auch über die dritte ComboBox filtern dann (SELECT * FROM ... WHERE ... AND ...) abgefragt werden.

ich würde mich freuen wenn mir jemand Helfen könnte.

Hier ist Code: für die Oberfläche diese wird in der Mainmethode nur aufgerufen und sichtbar gemacht.



Java:
package selction;

import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.swing.table.DefaultTableModel;

/**
 *
 *
 */
public class MainFrame extends javax.swing.JFrame {

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        überschrift1 = new javax.swing.JLabel();
        überschrift2 = new javax.swing.JLabel();
        LpSelectLabel = new javax.swing.JLabel();
        ifcComboBox = new javax.swing.JComboBox<>();
        ifcSelectLabel = new javax.swing.JLabel();
        LpComboBox = new javax.swing.JComboBox<>();
        AttributSelectLabel = new javax.swing.JLabel();
        AttributComboBox = new javax.swing.JComboBox<>();
        SuchButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblData = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        überschrift1.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
        überschrift1.setText("Schrobsdorff Bau AG");
        überschrift1.setPreferredSize(new java.awt.Dimension(40, 15));

        überschrift2.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N
        überschrift2.setText("Bauteilkatalog");
        überschrift2.setPreferredSize(new java.awt.Dimension(40, 15));

        LpSelectLabel.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
        LpSelectLabel.setText("Leistungsphase wählen:");

        ifcComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Wand", "Decke", "Stütze", "Träger" }));
        ifcComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
              
                
                
                
            
                
            }
            
        });

        ifcSelectLabel.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
        ifcSelectLabel.setText("ifcType wählen:");
        
        LpComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Lp3", "Lp4", "Lp5",}));
        LpComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
            }
        });

        AttributSelectLabel.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
        AttributSelectLabel.setText("Attribut wählen:");

        AttributComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Typ","Festigkeit","Oberflächenqualität"}));
        
            
        

      
        SuchButton.setText("Suchen");
        SuchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evnt) {
                try {
                    SuchButtonActionPerformed(evnt);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            
            }
        });
        
        
        

        tblData.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblData);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(59, 59, 59)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(AttributSelectLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ifcComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(überschrift2, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                    .addComponent(überschrift1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(LpSelectLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(ifcSelectLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(LpComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(AttributComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(SuchButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1260, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(überschrift1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(überschrift2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(45, 45, 45)
                        .addComponent(ifcSelectLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ifcComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(LpSelectLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(LpComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(AttributSelectLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(AttributComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(163, 163, 163)
                        .addComponent(SuchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

                                        
  
    
                
    private void SuchButtonActionPerformed(java.awt.event.ActionEvent evt) throws SQLException {
        String selectedIfcType = (String)ifcComboBox.getSelectedItem();
        String selectedLp = (String)LpComboBox.getSelectedItem();
        String selectedAttribut = (String)AttributComboBox.getSelectedItem();
        
        String url = "jdbc:mysql://localhost:3306/testtable?";
        String user = "Vinzenz";
        String password = "11ccffe1b5";
        

        if ( selectedIfcType != null && selectedLp == null && selectedAttribut == null ) {
            System.out.println("SELECT * FROM " + selectedIfcType);
            try(Connection conn = DriverManager.getConnection(url, user, password)){
                String query = "SELECT * FROM " + selectedIfcType;
                System.out.println(query);
                @SuppressWarnings("rawtypes")
                java.sql.Statement st = conn.createStatement();
                ResultSet rs = ((java.sql.Statement) st).executeQuery(query);
                
                ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
                DefaultTableModel model = (DefaultTableModel) tblData.getModel();
                
                int columns = rsmd.getColumnCount();
                String[] colName = new String[columns];
                for (int i = 0; i < columns; i++)
                    colName[i] = rsmd.getColumnName(i+1);
                model.setColumnIdentifiers(colName);
                String id, Leistungsphase, Attribut, Werte;
                while (rs.next()) {
                    id=rs.getString(1);
                    Leistungsphase=rs.getString(2);
                    Attribut=rs.getString(3);
                    Werte=rs.getString(4);
                    String [] row = {id, Leistungsphase, Attribut, Werte};
                    model.addRow(row);
                    
                }
                ((java.sql.Statement) st).close();
                conn.close();
                
                
                
                
                
                
            }
        }if ( selectedIfcType != null && selectedLp != null && selectedAttribut == null ) {
            System.out.println("SELECT * FROM " + selectedIfcType + " WHERE Leistungsphase = " + selectedLp);
            
            try(Connection conn = DriverManager.getConnection(url, user, password)){
                String query = "SELECT * FROM " + selectedIfcType + " WHERE Leistungsphase = " + selectedLp;
                System.out.println(query);
                @SuppressWarnings("rawtypes")
                java.sql.Statement st = conn.createStatement();
                ResultSet rs = ((java.sql.Statement) st).executeQuery(query);
                
                ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
                DefaultTableModel model = (DefaultTableModel) tblData.getModel();
                
                int columns = rsmd.getColumnCount();
                String[] colName = new String[columns];
                for (int i = 0; i < columns; i++)
                    colName[i] = rsmd.getColumnName(i+1);
                model.setColumnIdentifiers(colName);
                String id, Leistungsphase, Attribut, Werte;
                while (rs.next()) {
                    id=rs.getString(1);
                    Leistungsphase=rs.getString(2);
                    Attribut=rs.getString(3);
                    Werte=rs.getString(4);
                    String [] row = {id, Leistungsphase, Attribut, Werte};
                    model.addRow(row);
                    
                }
                ((java.sql.Statement) st).close();
                conn.close();
                
                
                
                
                
                
            }
        }if ( selectedIfcType != null && selectedLp != null && selectedAttribut != null ) {
            System.out.println("SELECT * FROM " + selectedIfcType + " WHERE Leistungsphase = " + selectedLp + " AND Attribut " + selectedAttribut);
            try(Connection conn = DriverManager.getConnection(url, user, password)){
                String query = "SELECT * FROM " + selectedIfcType + " WHERE Leistungsphase = " + selectedLp + " AND Attribut " + selectedAttribut;
                System.out.println(query);
                @SuppressWarnings("rawtypes")
                java.sql.Statement st = conn.createStatement();
                ResultSet rs = ((java.sql.Statement) st).executeQuery(query);
                
                ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
                DefaultTableModel model = (DefaultTableModel) tblData.getModel();
                
                int columns = rsmd.getColumnCount();
                String[] colName = new String[columns];
                for (int i = 0; i < columns; i++)
                    colName[i] = rsmd.getColumnName(i+1);
                model.setColumnIdentifiers(colName);
                String id, Leistungsphase, Attribut, Werte;
                while (rs.next()) {
                    id=rs.getString(1);
                    Leistungsphase=rs.getString(2);
                    Attribut=rs.getString(3);
                    Werte=rs.getString(4);
                    String [] row = {id, Leistungsphase, Attribut, Werte};
                    model.addRow(row);
                    
                }
                ((java.sql.Statement) st).close();
                conn.close();
                
            }
            
        }
                
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    public javax.swing.JComboBox<String> AttributComboBox;
    private javax.swing.JLabel AttributSelectLabel;
    public javax.swing.JComboBox<String> LpComboBox;
    private javax.swing.JLabel LpSelectLabel;
    private javax.swing.JButton SuchButton;
    public javax.swing.JComboBox<String> ifcComboBox;
    private javax.swing.JLabel ifcSelectLabel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblData;
    private javax.swing.JLabel überschrift1;
    private javax.swing.JLabel überschrift2;
    // End of variables declaration                   
}
 
Was ist denn das genaue Problem? Was für Fehler bekommst Du? Oder an welcher Stelle kommst Du genau nicht weiter?

Der Code ist extrem unübersichtlich - alleine schon SuchButtonActionPerformed mit über 100 Zeilen ... und darin dann 3 Blöcke mit (fast) identischem Code - da wäre ein Refactoring bestimmt nicht schlecht 🙂

Ist das Problem evtl. ein ungültiges SQL Statement? Das SQL Query sieht erst einmal nicht korrekt aus, das Du da baust.
 
Mein Problem liegt soweit ich weiß in den If-Bedingungen vom SuchButtonActionPerformed in den Zeilen: 185, 221, 258 .
Hier ist mein ziel nur den Query zu erzeugen welcher von den welcher von der suche ausgewählt worden ist, ist zb. nur in der ersten beiden Comboboxen etwas ausgewählt, dann wird ein Query zweiter ebene erstell : (SELECT * FROM ... WHERE ...).

Bitte entschuldigt meine unübersichtlich Programmierskills 😅
 
Also im Augenblick sehe ich da prinzipiell kein Problem. Du hast JCoboBox Instanzen. Du rufst auf diesen getSelectedItem auf und das sollte null zurück geben, wenn kein Wert ausgewählt wurde.

Du kannst ja testweise einmal ausgeben, was da für Werte stehen, also etwas wie:
Java:
        String selectedIfcType = (String)ifcComboBox.getSelectedItem();
        String selectedLp = (String)LpComboBox.getSelectedItem();
        String selectedAttribut = (String)AttributComboBox.getSelectedItem();
        System.out.println(selectedIfcType + " / " + selectedLp + " / " + selectedAttribut);

Dann ist die Frage bezüglich des Aufbaus bei Deinem Code. Ich sehe da prinzipiell keine Probleme, aber man kann da ja durchaus ein paar erste Dinge umschreiben:

a) Vereinfachung der Prüfungen - wenn selectedIfcType null ist, dann soll ja nichts gemacht werden. Also kann man das einfach schreiben als:

Java:
if (selectedIfcType == null) {
    System.out.println("No type selected..."); // Einfach eine Debug Ausgabe ... sollte normalerweise ein Log Eintrag sein oder so ....
    return; // Methode verlassen
}

// Ab hier muss man selectedIfcType nicht mehr auf != null prüfen, denn das ist ja jetzt hier sicher gestellt.

...

b) In Deinen einzelnen if Anweisungen hast Du immer den Aufbau einer Query und dann die Ausführung der Query. Die Ausführung kann z.B. in eine eigene Methode, die Du aufrufst und der Du einfach die query übergibst.

c) Das Statement st = conn.createStatement(); kannst Du in das try with resources der Connection mit rein packen - dann brauchst Du da auch kein close Aufruf mehr.

Ich hab es gelöst bekommen =).

Vielen Dank dennoch 🙂
Das ist super - kannst Du evtl. auch kurz schreiben, an welcher Stelle das Problem war?
 
Ich konnte das Problem lösen indem ich für meine als erstes Item ein "null" nehme und dann die Anderen Items da ich in den Jeweiligen If Bedingungen ja auch nach "null" filter

Java:
JComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1","Item 2","Item 3"}));
if ( selectedIfcType != null && selectedLp == null && selectedAttribut == null )

was dann so aussieht:

JComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { null, "Item 1","Item 2","Item 3"}));
 

Neue Themen


Zurück
Oben