2

I'm having a problem with GUI. When I click on JButton b1, when the text is empty in the JTextField text it does not catch the exception.

The query is executing only once when the button is clicked,if clicked again it throws exception and query is not executing

Code:

public class A extends JFrame{


    private JTextField text;
    private JButton b1;
    private JLabel l1;
    private Connection conn;
    private Statement state;
    private ResultSet set;

    String server = "jdbc:mysql://localhost";
    String user="tim";
    String pass="u";
    //query enter in textfield | select * from universty.student where rollno=2

    public A() throws ClassNotFoundException, SQLException{

        super("Frame");
           Class.forName("com.mysql.jdbc.Driver");
                    conn = DriverManager.getConnection(server,user,pass);

                    state = conn.createStatement();

                    getContentPane().setLayout(null);




        text = new JTextField();
        text.setBounds(35, 132, 346, 35);
        getContentPane().add(text);

        l1= new JLabel();
        l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
        l1.setBounds(35, 305, 384, 27);
        getContentPane().add(l1);


        b1 = new JButton("Submit");
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                try{

            String  query = text.getText();

                set = state.executeQuery(query);


            set.next();
            String  answer = set.getString(2);


               l1.setText(answer);          





                }
                catch (Exception e){
                    JOptionPane.showMessageDialog( null, 
                            e.getMessage(), "Database error", 
                            JOptionPane.ERROR_MESSAGE );            
                    return;
                }
                finally{
                    try{
                        set.close();
                        state.close();
                        conn.close();

                    }
                        catch(Exception e){
                            e.printStackTrace();
                        }

                }

            }});
        b1.setBounds(132, 178, 129, 35);
        getContentPane().add(b1);






        setSize(450,450);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);

    }   

}

Main Method:

public class Main {

    public static void main(String args[]) throws ClassNotFoundException, SQLException{

    A obj = new A();

    }

}
2
  • throws in your main method has a really bad taste. Use your try/catch block to handle your exceptions. Commented Jun 30, 2015 at 8:44
  • Also, you're mixing DB code with GUI code, generally not a good idea, you should separate this out in to a service and DAO layer Commented Jun 30, 2015 at 9:14

3 Answers 3

2

You should open and close the database connection within your:

actionPerformed()

Since when you call your constructor it opens the db connection and closes it again. When you click the db connection is already closed again

public void actionPerformed(ActionEvent arg0) {
      conn = DriverManager.getConnection(server,user,pass);
      state = conn.createStatement();
      //do query here
      set.close();
      state.close()
      conn.close();
}
Sign up to request clarification or add additional context in comments.

2 Comments

open and close the database connection within your actionPeformed method
thanx for help Peter P i understand your answer
0

At the end of the first click, you close everything with following statement.

            finally{
                try{
                    set.close();
                    state.close();
                    conn.close();

That's why.

__UPDATE__

I am asked to provide a solution. Actually I have given half of the solution by pin-pointing the problem. But let me elaborate more, since I am asked.

Simple solution is not to close connection or statement or whatever. But this would be a bad solution, as unnecessary resources could be hold active. No need for that.

I do not know your application. So I can not give you a precise answer but rather, I can give you some guide lines and help you find the right answer by yourself.

Hold on to the resources, as long as you need them. And get rid of them as soon as you are done with them. For this case, If it is required user to click on that button and make a change in the database, then do not close connection etc but reuse them. If it is a multi-page application, you can close these resource when user moves to another page. (or activity if it a mobile app).

I hope it makes sense =]

1 Comment

so what is the solution
0

I'm not sure of the purpose of your code but you should try and separate your view logic from your business logic. Also allowing a user to run SQL from a text box and submit button sounds dangerous, but if that's really what you want to do, here is one implementation you could use. Note the DAO here is not a true DAO because of the way you want to execute a query

    public class A extends JFrame {

        private final JTextField text;
        private final JButton b1;
        private final JLabel l1;

        private AService service;

        public A() {
            super("Frame");
            service = new AServiceImpl(new ADAOJDBCImpl());
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }

        private static void createAndShowGUI() {
            text = new JTextField();
            text.setBounds(35, 132, 346, 35);
            getContentPane().add(text);

            l1= new JLabel();
            l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
            l1.setBounds(35, 305, 384, 27);
            getContentPane().add(l1);

            b1 = new JButton("Submit");
            b1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                       String  query = text.getText();
                       try {
                           String answer = service.executeQuery(query);
                           l1.setText(answer);
                       } catch (SQLException e){
                        JOptionPane.showMessageDialog( null, 
                                e.getMessage(), "Database error", 
                                JOptionPane.ERROR_MESSAGE );            
                        return;
                    }

                }});
            b1.setBounds(132, 178, 129, 35);
            getContentPane().add(b1);
            setSize(450,450);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setResizable(false);
            pack();
            setVisible(true);
        }
    }

    public interface AService {
        public String executeQuery(String query) throws SQLException;
    }

    public class AServiceImpl implements AService {

        private ADAO dao;

        public AServiceImpl(ADAO dao) {
            this.dao = doa;
        }

        @Override
        public String executeQuery(String query) throws SQLException {
            return dao.executeQuery();
        }

    }

    /**
    * Note usually a DAO is specfically for accessing data, NOT
    * for executing User defined queries from a GUI text box
    * so it would usually have methods such as add, find, delete, update etc.
    */
    public interface ADAO {
        public String executeQuery(String query) throws SQLException;
    }

    public class ADAOJDBCImpl implements ADAO {

        @Override
        public String executeQuery(String query) throws SQLException {
            String server = "jdbc:mysql://localhost";
            String user="tim";
            String pass="u";            

            String answer = "":
            try (Connection conn = DriverManager.getConnection(server,user,pass);
                 Statement state = conn.createStatement();
                 ResultSet set = state.executeQuery(query);) {

                if(set.next()) {
                    answer = set.getString(2);
                }
            }
            return answer;
        }

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.