0

学生のデータベースを検索し、検索結果をオプション ペインに表示するコードを作成しようとしました。そして、次のように書くに至りました。期待される結果は次のとおりです。

名前:「何か」 ロール:「何か」 登録:「何か」

しかし、実際の出力は次のようになります。

名前: null ロール: null 登録: 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();
}

}

4

2 に答える 2

0
  1. Class.forName は、クラスに対してコンパイルする必要なく、ドライバー クラスがクラス パス上にあることを保証します。クラスをロードします。インスタンス化は必要ありません。
  2. PreparedStatement は、SQL インジェクションに対して優れています。
  3. SQL API の列番号は 1 から始まります: 1、2、3、...少し例外があります。
  4. firstクエリループを使用する場合は次のとおりです。あなたは最初の行をスキップしたと思います。
  5. その他のことを忘れないでくださいclose()
  6. `*' の代わりに列をリストするより良いスタイル。

したがって:

        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);
于 2013-07-22T11:22:25.450 に答える
0

デバッガーを使用して、コードのどの部分が省略されているかを確認します。私が見る奇妙なことの 1 つは、結果セットの最初のレコードにジャンプすることです。

rs.first();

その後、while ループで後続のすべてのレコードからデータを読み取ります。

 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())

于 2013-07-22T11:00:38.340 に答える