我正在制作一个 GUI,用户可以在其中输入任何电影名称。如果数据库有该电影,那么它会出现在 ide 控制台上,如果没有,则显示消息。现在,当用户输入任何相关电影时,程序会在 ide 控制台上给出正确的输出位于数据库中。但问题是,当输入数据库中没有的任何错误电影名称时,程序不会执行任何操作。当从数据库中找不到任何内容时,我想给出一条 JOptionPane
消息,就像这个
以及何时找到数据。
但我不知道该怎么做。
代码:
public class Find extends JFrame{
private JLabel keyword;
private JTextField tx;
private JComboBox box;
private Connection conn;
private PreparedStatement pre;
private ResultSet set;
private ResultSetMetaData meta;
String server = "jdbc:mysql://localhost/demo";
String user="root";
String pass="pass";
public Find(){
super("Frame");
getContentPane().setLayout(null);
keyword= new JLabel("Keyword");
keyword.setBounds(170, 100, 96, 37);
getContentPane().add(keyword);
box = new JComboBox();
box.setModel(new DefaultComboBoxModel(new String[] {"Title"}));
box.setBounds(42, 139, 63, 20);
getContentPane().add(box);
//textfield
tx= new JTextField();
tx.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent arg0) {
try{
conn=DriverManager.getConnection(server,user,pass);
String option = (String) box.getSelectedItem();
String query = "select title,year from movies where "+option+"=?";
//statement
pre = conn.prepareStatement(query);
pre.setString(1, tx.getText());
set= pre.executeQuery();
ResultSetMetaData meta = set.getMetaData();
int totalcolumn=meta.getColumnCount();
while(set.next()){
for(int i=1;i<=totalcolumn;i++){
System.out.printf("%-8s\t", set.getObject(i));
}
System.out.println();
}
}
catch(Exception e1){
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
});
tx.setBounds(120, 136, 202, 27);
getContentPane().add(tx);
setSize(450,450);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(false);
setVisible(true);
}
}
主要
public class FindMain {
public static void main(String[] args) {
Find ooper = new Find();
}
}
最佳答案
您想要检查查询是否返回空结果集。如果光标未位于第一行之前或者集合不包含行
,则 isBeforeFirst() 方法返回 falseif (!set.isBeforeFirst()) {
//Here you can display your 'failure' JOptionPane
}
else {
//Here you can put your code that handles your set, including your 'success' JOptionPane
}
例如,我会建议进行此更改:
...
set = pre.executeQuery();
if (!set.isBeforeFirst()){
JOptionPane.showMessageDialog(null, "The record was not found.");
}
else{
ResultSetMetaData meta = set.getMetaData();
int totalcolumn=meta.getColumnCount();
while(set.next()){
for(int i=1;i<=totalcolumn;i++){
System.out.printf("%-8s\t", set.getObject(i));
}
System.out.println();
}
}
}
catch(Exception e1){
...
关于Java 如何在方法上添加 JOptionPane 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31189237/