1

How to navigate through and display each database record in the 'textfield' using an AWT button?

I'm trying the make a Java form to navigate through the database records, such that when the 'next' button is pressed, each subsequent hit fetches the next database record into the respective textfields. The problem with this code is no matter how many times I press the next button, only the first record is displayed in the textfields.

I've read on several threads that if(rs.next()) condition will not work in such case. What could be the right fix for this and why?

PS: I've marked the problematic area within Problem code begins and Problem code ends.

import java.awt.Button;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JOptionPane;

public class ManageEmployees implements ActionListener
{
    Connection con;

    Statement st;

    ResultSet rs;

    Frame f;

    Choice employeeID;

    Button savenewemployeeButton, updateemployeeButton, returndashboardButton, nextButton/*, previousButton, lastButton, firstButton*/;

    Label nameLabel, usernameLabel, addressLabel, contactnumberLabel, passwordLabel, confirmpasswordLabel, selectemployeeLabel;

    TextField nameTextField, usernameTextField, addressTextField, passwordTextField, confirmpasswordTextField;

    ManageEmployees()
        {
            dbconnect();
            initframe();        
        }

    public void dbconnect()
    {
        try{

        Class.forName("com.mysql.jdbc.Driver");

        con=DriverManager.getConnection("jdbc:mysql://localhost:8889/InventoryManagement","root","root");

        st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

        String sql="select * from SalesMen";

        rs=st.executeQuery(sql);

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

    public void initframe()
    {
        f=new Frame("Manage Employees");

        selectemployeeLabel=new Label("Select Employee Type:");
        nameLabel=new Label("Employee Name:");
        addressLabel=new Label("Address:");
        usernameLabel=new Label("User Name:");
        passwordLabel=new Label("Password:");
        confirmpasswordLabel=new Label("Confirm Password:");

        employeeID=new Choice();

        employeeID.add("Sales Person");
        employeeID.add("Sales Manager");
        employeeID.add("Inventory Manager");
        employeeID.add("Administrator");

        savenewemployeeButton=new Button("Save New Employee details");
        savenewemployeeButton.addActionListener(this);
        returndashboardButton=new Button("Return to Dashboard");
        returndashboardButton.addActionListener(this);

        nextButton=new Button("Next");
        nextButton.addActionListener(this);

        nameTextField=new TextField(30);
        addressTextField=new TextField(50);
        usernameTextField=new TextField(20);
        passwordTextField=new TextField(15);
        confirmpasswordTextField=new TextField(15);

        f.setLayout(new GridLayout(10,2,0,2));

        f.add(selectemployeeLabel);
        f.add(employeeID);

        f.add(nameLabel);
        f.add(nameTextField);

        f.add(addressLabel);
        f.add(addressTextField);

        f.add(usernameLabel);
        f.add(usernameTextField);

        f.add(passwordLabel);
        f.add(passwordTextField);

        f.add(confirmpasswordLabel);
        f.add(confirmpasswordTextField);

        f.add(returndashboardButton);
        f.add(savenewemployeeButton);
        f.add(nextButton);

        passwordTextField.setEchoChar('*');
        confirmpasswordTextField.setEchoChar('*');

        f.setSize(500,400);
        f.setVisible(true);
        f.setResizable(false);


        f.addWindowListener(new WindowAdapter()
        {

            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        }
        );
    }

    public void actionPerformed(ActionEvent e)
    {

        // Return to dashboard on button click

        if(e.getSource()==returndashboardButton)
        {
            f.dispose();
            new Dashboard();
        }

        // ---------------------------------------- (Begin) Save new employee information ------------------------------------------------------------//    

       // Save new Sales Person information  

        String salesmen=employeeID.getSelectedItem();


        if(salesmen=="Sales Person" && e.getSource()==savenewemployeeButton)
        {

            try
            {       
                String fullname1=nameTextField.getText();
                String address1=usernameTextField.getText();
                String username1=addressTextField.getText();
                String password1=passwordTextField.getText();

                String sql="insert into SalesMen values('"+fullname1+"','"+address1+"','"+username1+"','"+password1+"')";
                st.executeUpdate(sql);

                JOptionPane.showMessageDialog(null,"New Sales Man's details saved!");

            }

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

        }

           // Save new Sales Manager information  

        String salesmanager=employeeID.getSelectedItem();

        if(salesmanager=="Sales Manager" && e.getSource()==savenewemployeeButton)
        {
            try
            {

                String fullname1=nameTextField.getText();
                String address1=usernameTextField.getText();
                String username1=addressTextField.getText();
                String password1=passwordTextField.getText();

                String sql="insert into SalesManagers values('"+fullname1+"','"+address1+"','"+username1+"','"+password1+"')";
                st.executeUpdate(sql);

                JOptionPane.showMessageDialog(null,"New Sales Manager's details saved!");

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

           // Save new Inventory Manger information  


        String inventorymanger=employeeID.getSelectedItem();

        if(inventorymanger=="Inventory Manager" && e.getSource()==savenewemployeeButton)
        {
            try
            {

                String fullname1=nameTextField.getText();
                String address1=usernameTextField.getText();
                String username1=addressTextField.getText();
                String password1=passwordTextField.getText();

                String sql="insert into InventoryManagers values('"+fullname1+"','"+address1+"','"+username1+"','"+password1+"')";
                st.executeUpdate(sql);

                JOptionPane.showMessageDialog(null,"New Inventory Manager's details saved!");

            }

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

           // Save new Administrator information  


        String administrator=employeeID.getSelectedItem();

        if(administrator=="Administrator" && e.getSource()==savenewemployeeButton)
        {
            try
            {
                String fullname1=nameTextField.getText();
                String address1=usernameTextField.getText();
                String username1=addressTextField.getText();
                String password1=passwordTextField.getText();

                String sql="insert into Administrators values('"+fullname1+"','"+address1+"','"+username1+"','"+password1+"')";
                st.executeUpdate(sql);

                JOptionPane.showMessageDialog(null,"New Admin's details saved!");

            }

                catch(Exception ce)
                {
                    ce.printStackTrace();
                }
            // ---------------------------------------- (End) Save new employee information ------------------------------------------------------------//          
        }

        if(salesmen=="Sales Person" && e.getSource()==nextButton)
        {
                 try
                    {   
                        String sql="select * from SalesMen";
                        rs=st.executeQuery(sql);

                      // Problem code begins 

                        if(rs.next())
                        {

                            nameTextField.setText(rs.getString("FullName")); 
                            usernameTextField.setText(rs.getString("UserName"));
                            addressTextField.setText(rs.getString("Address")); 

                        }

                       else

                        {
                            rs.previous();
                            System.out.println("boo!");
                            JOptionPane.showMessageDialog(null,"No more records");
                        }  

                    }

                           // Problem code ends 

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


        }

    } 

    public static void main(String[] args) 
    {   
           new ManageEmployees();
    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
rajagrawal
  • 622
  • 4
  • 14
  • 26
  • 1
    Why AWT rather than Swing? See this answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. If you need to support older AWT based APIs, see [Mixing Heavyweight and Lightweight Components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). – Andrew Thompson Jun 26 '13 at 14:18
  • Thanks! The threads are helpful! – rajagrawal Jun 26 '13 at 17:31
  • A simple approach that I tested and found working is at http://stackoverflow.com/a/15819342/1539820 – rajagrawal Jun 27 '13 at 05:31

2 Answers2

3
  • use Swing JComponents rather than AWT Components

  • use JTable instead of sets of AWT TextFields

  • search for ResultSetTableModel or TableFromDatabase for easy, stable and correct workaround

  • ResultSetTableModel, TableFromDatabase or your idea has an issue with Event Dispatch Thread

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Thanks mKorbel! I'll begin learning them. But, can you point out what could be changed in the code above, in order to make it work according to the desired concern? A correct version of the code, if possible? – rajagrawal Jun 26 '13 at 17:28
  • 1
    would need to load (reasonable number of recods) to the array, then loop inside array (JButton click), after any changes will be array refreshed with updated records from database, – mKorbel Jun 26 '13 at 18:38
0

Okay, despite the useful answers people have given; after trial and error, i've found a more appropriate answer to the question. The "if(rs.next())" condition DOES WORK to navigate the database records forward, if used correctly. It works perfectly fine with either AWT or SWING. The problem occurs by inappropriately placing the following lines of code:

/* Remember to carefully use and place the following code in your program*/

String sql="select * from Tablename";
rs=st.executeQuery(sql);

So with reference to the program in this question, notice that the two lines of code above are already called once during program's lifetime when dbconnect() function is called by the constructor. Now pay attention because here's where the problem begins. *The two strings highlighted above are redundantly trigged each time when the 'next button' is hit, thus each time resetting the resultset, and logically disallowing 'rs.next()' to move to the next record. So, only placing those two lines of code once in the dbconnect() function does the job correctly.*

rajagrawal
  • 622
  • 4
  • 14
  • 26