Java – Fetch data from database into Jtextfield when One Jtextfield is Typed

autocompletejavaoracle11gswing

Hi Guys I have a Swing Application that is connected to an oracle database, I want it such that Once I type a Value into the JTextField, the other JTextfields on the JFrame are loaded with subsequent data from the database but I do not seem to achieve this. I have tried the Following code but it fetched nothing.

txtNo.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent ke) {
            Connection conn = null;
            try{
                Class.forName("oracle.jdbc.driver.OracleDriver");

        conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "Username", "Password");
        Statement st = conn.createStatement();
        String load = "Select * from Store_info_table where PART_NUMBER = '" + txtNo.getText() + "'";
        ResultSet rs = st.executeQuery(load);
        while(rs.next()){
            txtName.setText(rs.getString("SPARE_DESC"));
        }
            }catch(Exception ae){

            }
        }
    });

Best Answer

  • Replace the KeyListener by a DocumentListener
  • The database connection on the EDT is a bad idea (too slow). Consult the concurrency in Swing guide for more information
  • You are vulnerable to SQL injection
  • Avoid empty catch statements or you have no idea that something is going wrong. If you do not opt for decent error handling, at least log the stack trace (either by just printing it, or by using a Logger).
Related Topic