我试图编写一个搜索学生数据库并在选项窗格上显示搜索结果的代码。我最终写了以下内容。预期结果是:
姓名:“某事” 卷:“某事” 注册:“某事”
但实际上输出是这样的:
姓名:空卷:空注册:空
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();
}
}