Get mysql table id in application

0

I'm developing a Java application where I need to retrieve the id of a Course table (idCourse, CourseName, CourseCode). I'm trying to do the following:

public class Teste4 extends javax.swing.JFrame {

        Connection con = new ConnectionFactory().getConnection();
        int id = 0;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        String query = "SELECT idCurso FROM Curso WHERE nomeCurso = "
                + "' xiu ' AND tipoCurso = "
                + "' Técnico '";
        try{
            PreparedStatement stmt = con.prepareStatement(query);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()){
                id = rs.getInt("idCurso");
            }
        }catch (SQLException ex){
            ex.printStackTrace();
        }
        this.id = id;
    }

    public Teste4() {


        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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(170, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(157, 157, 157))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(139, 139, 139)
                .addComponent(jButton1)
                .addContainerGap(138, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JFNovoCurso janela = new JFNovoCurso();
        System.out.println(getId());
        janela.setId(getId());
        janela.setVisible(true);
    }                                        

    /**
     * @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(Teste4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Teste4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Teste4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Teste4.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 Teste4().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

The result of this query is 0, and when I do the same query in mysql it returns some value to the id, so I guess it's not syntax.

ConnectionFactory Class:

public class ConnectionFactory {

    Connection con;

    public Connection getConnection(){

        String url = "jdbc:mysql://localhost:3306/tcc";
        try {
            return (Connection) DriverManager.getConnection(url,"root", "GUstavo08!");
        }catch(SQLException ex){
            System.out.println("Problemas na conexão " + ex.getMessage());
            return null;
            }
    }

}
    
asked by anonymous 21.06.2018 / 00:35

2 answers

0

See that there are spaces in your parameters and how you are using = will not work.

Modify the line to look exactly as below:

String query = "SELECT idCurso FROM Curso WHERE nomeCurso = 'xiu' AND tipoCurso = 'Técnico'";
    
21.06.2018 / 01:14
0

I think the problem is in the space between the ' Xiu ' and ' Técnico ' quotation marks. When it executes the PreparedStatement, by conciderar these spaces, it ends up not finding any tuple that corresponds returning an empty ResultSet. In addition I propose the following changes in your code:

  • Using the setString() methods of the PreparedStatement object
  • As in this case only one tuple should be returned so instead of a while (rs.next()) use if(rs.next()
  • The id parameter of the setId(int id) method ends up not being used but forces you to invoke this method to set a variable that will not do anything, it would be better if the method did not receive parameters and you defined a local variable. >

    The code looks like this:

    public void setId() {
        int aux = 0;
        String query = "SELECT idCurso FROM Curso WHERE nomeCurso = ? AND tipoCurso = ?;";
        try{
            PreparedStatement stmt = con.prepareStatement(query);
    
            stmt.setString(1, "Xiu");
            stmt.setString(2, "Técnico");
    
            ResultSet rs = stmt.executeQuery();
            if(rs.next()) aux = rs.getInt("idCurso");
    
        }catch (SQLException ex){
            ex.printStackTrace();
        }
        this.id = aux;
    }
    
        
  • 21.06.2018 / 01:18