简体   繁体   中英

How can I pass string to a JOptionPane?

I have tried to write a code that searches a database of students and shows the searched result on a option pane. And I ended up writing the following. The expected result is:

Name: "something" Roll: "something" Registration: "Something"

But actually the output is something like this:

Name: null Roll: null Registration: null


public class Search

{

JFrame sw = new JFrame("Search Students' Info");   //search window
JTable stable;
JLabel stfl = new JLabel("Roll");                  //search text field label
JTextField stf = new JTextField(8);               //search text field


JButton sb = new JButton("Search");             //search button

public void exsearch()                              //Execute Search
{
    sw.setLayout(new GridLayout(2,2));
    sw.add(stfl);
    sw.add(stf);
    sw.add(sb);


    sw.setSize(200, 100);
    sw.setLocation(100, 100);
    sw.setVisible(true);

    sb.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost/srsdb";
            try
            {
                Class.forName(driver).newInstance();

                java.sql.Connection con = DriverManager.getConnection(url, "root", "");
                JOptionPane.showMessageDialog(null, "Connected", "Connection Confirmation", JOptionPane.PLAIN_MESSAGE);

                String str ="SELECT* FROM students WHERE Roll="+stf.getText();
                java.sql.Statement st = con.createStatement();
                java.sql.ResultSet rs = st.executeQuery(str);

                rs.first();

                int n = rs.getMetaData().getColumnCount();
            //  String[] columnnNames;
                String[] attributes= new String[10];

                int j;

                while(rs.next())
                {
                    for(j=0; j<3; j++)
                    {
                        attributes[j] = rs.getString(j);
                    }
                }
                    JOptionPane.showMessageDialog(null, "Name :"+attributes[0]+"\nRoll :"+attributes[1]+"\nRegistration :"+attributes[2], "Search Result", JOptionPane.PLAIN_MESSAGE);
            }
        catch(Exception f)
        {
            f.printStackTrace();
            JOptionPane.showMessageDialog(null, "Not Found", "Search Result", JOptionPane.PLAIN_MESSAGE);
        }   

    }});


}

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

}

I would use a debugger to check which part of your code is omitted. One wierd thing I see is, that you jump to the first record in your result set:

rs.first();

And then you read the data from all subsequent records in a while loop

 while(rs.next())
 {
    for(j=0; j<3; j++)
    {
        attributes[j] = rs.getString(j);
    }
 }

This ensures, that you get the data from the last matching record if there is more than one. Better would be to check if there is zero or more than one record. If that is the case, issue a warning because probably there is something wrong with your code (use a debugger to find out what). If there is only one record, read the data from that record and print it (more or less like you try with rs.getString())

  1. Class.forName ensures that the driver class is on the class path, without needing to compile against the class. It loads the class. No instantiation needed.
  2. A PreparedStatement is better against SQL injection .
  3. Column numbers in the SQL API are 1-based: 1, 2, 3, ... A bit of an exception.
  4. When using first the query loop is as follows. You skipped the first row I think.
  5. Do not forget the miscellaneous close() .
  6. Better style to list the columns instead of `*'.

Hence:

        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost/srsdb";
        try
        {
            Class.forName(driver);

            Connection con = DriverManager.getConnection(url, "root", "");
            JOptionPane.showMessageDialog(null, "Connected",
                "Connection Confirmation", JOptionPane.PLAIN_MESSAGE);

            String str ="SELECT Name, Registration FROM students WHERE Roll=?";
            PreparedStatement st = con.createPreparedStatement(str);

            String roll = stf.getText();
            st.setString(1, roll);

            String message = "";
            java.sql.ResultSet rs = st.executeQuery();            
            int recno = 0;    
            if (rs.first()) {
                do {
                    String name = rs.getString(1);
                    String registration = rs.getString(2);
                    ++recno;
                    message += "- " + recno + " -\nName: " + name
                        + "\nRoll: " + roll
                        + "\nRegistration: " + registration + "\n";
                } while (rs.next());
            }
            rs.close();

            JOptionPane.showMessageDialog(null, message, "Search Result",
                JOptionPane.PLAIN_MESSAGE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM