ASH
ASH

Reputation: 63

JAVA and SQL, Cant store info in mysql server

The information that I enter in my java application is not creating a row in mysql server. I can connect with no problem with mysql server. I struggling to fix this problem.

Here is my first class that handles the connection between mysql and java

 public class MySqlConnect {
    Connection conn=null;
    public static Connection ConnectDB(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/singindbase","root","");
            JOptionPane.showMessageDialog(null,"Connected to database");
            return conn;
        }
    catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
    return null;
     }
  }
}

Here is my second class

    public class SignUp extends javax.swing.JFrame {
    Connection conn=null;
    PreparedStatement pst=null;
    private String Sql;

    /**
     * Creates new form SignUp
     */
    public SignUp() {
        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() {

        textid = new javax.swing.JTextField();
        textusernameR = new javax.swing.JTextField();
        textpasswordR = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("ID");

        jLabel2.setText("Username");

        jLabel3.setText("Password");

        jButton1.setText("Submit");
        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(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(textpasswordR, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                        .addComponent(textusernameR)
                        .addComponent(textid)))
                .addContainerGap(84, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(73, 73, 73)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textusernameR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textpasswordR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(35, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         


    conn=MySqlConnect.ConnectDB();
    String sql;    
        sql = "insert into login values(?,?,?)";

        try {

            pst=conn.prepareStatement(sql);
            pst.setString(1,textid.getText());
            pst.setString(2,textusernameR.getText());
            pst.setString(3,textpasswordR.getText());

            pst.execute();

            JOptionPane.showMessageDialog(null,"Account created sucessfully");

        } catch (SQLException e) {
        }

    }                                        

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField textid;
    private javax.swing.JPasswordField textpasswordR;
    private javax.swing.JTextField textusernameR;
    // End of variables declaration                   
}

The problem is that I cant populate the tables in MySQL database

enter image description here

Upvotes: 0

Views: 72

Answers (2)

Sami
Sami

Reputation: 93

As @Vishnu KR mentioned, printing the stack trace will give you important information about what's going wrong. I personally also like using the debugger to check exactly what my final SQL statement is before executing it.

Upvotes: 1

Vishnu KR
Vishnu KR

Reputation: 818

I would like recommend few things

  1. Please don't forgot to print the exception stack trace.
  2. Before inserting data you have to print those data console, this is just to confirm that you are going to insert proper data into the database and once it is done remove the printing command.

3.Specify the column in an insert query is always a best idea.

So please check the below code.

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  conn=MySqlConnect.ConnectDB();
  System.out.println("id"+textid.getText()+" username"+textusernameR.getText()+" password"+textpasswordR.getText()); // print the data (please take this to a DTO class would be better)
  String sql ="insert into login(column1,column2,column3)values(?,?,?)";// please mention the coulmn name
  try {
    pst=conn.prepareStatement(sql);
    pst.setString(1,textid.getText());// if id is an integer column you will get error here
    pst.setString(2,textusernameR.getText());
    pst.setString(3,textpasswordR.getText());
    boolean flag = pst.execute();//this will return true or false
    //pst.executeUpdate() it will return effected row number i prefer this method always for DDL commands
    if(flag )JOptionPane.showMessageDialog(null,"Account created sucessfully");
    else JOptionPane.showMessageDialog(null,"Account creation failed");

   } catch (SQLException e) {
       e.printStackTrace(); // print the stack trace
    }

}

I hope my explanation will help you.

Upvotes: 1

Related Questions