java - 如何知道 JFileChooser 是否为 null 以及如果为 null 则不更新数据库

标签 java netbeans jfilechooser

这是我的代码

    private void UploadActionPerformed(java.awt.event.ActionEvent evt) {                                       
    JFileChooser Attach = new JFileChooser();
    try {
        if (Attach.showOpenDialog(Upload) == JFileChooser.APPROVE_OPTION) {
            File ImageFile = Attach.getSelectedFile();
            lbl_Image.setIcon(new ImageIcon(ImageFile.toString()));
            lbl_Image.setHorizontalAlignment(JLabel.CENTER);

            filename = ImageFile.getAbsolutePath();

            try {
                File Image = new File(filename);
                FileInputStream fis = new FileInputStream(Image);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                for (int readNum; (readNum = fis.read(buf)) != -1;) {
                    bos.write(buf, 0, readNum);
                }
                person_image = bos.toByteArray();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}          

然后这是我更新数据库的代码

                con = DriverManager.getConnection(Module.url, Module.username, Module.password);
                String sql = "Update resume set Image = ?, FirstName = ? where ID = '" + ID.getText() + "'";
                ps = con.prepareStatement(sql);
                ps.setBytes(1, person_image);
                ps.setString(2, WordUtils.capitalizeFully(Fname.getText()));
                ps.executeUpdate();

我想知道,如果用户想要更新数据库中的数据并且他没有在 JFileChooser 上选择任何文件,那么数据库中的 Image(Blob) 字段不应更新,我该如何编写程序。

因为在我的代码中,如果用户未在 JFileChooser 上选择任何文件,则 Image(Blob) 字段将更新为 NULL。

最佳答案

您可以像这样检查 person_image 数组是否为 null

if (person_image != null) {
  // Now do whatever you want to do !!
}
else{
  throw new ImageNotSelectedCustomException(); // this is your custom exception
  // you can also simply ignore it and do another piece of work
}

注意:请阅读一些basic tutorial on Java ,因为检查 Null 并不是什么大问题,如果您可以自己编写这么多代码。

关于java - 如何知道 JFileChooser 是否为 null 以及如果为 null 则不更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29646435/

相关文章:

java - Java中的线程同步

java - Eclipse 的 $FALL-THROUGH$ 评论标准吗?

tomcat - 如何配置 Maven 配置文件以在 tomcat 或来自 netbeans 6.9.1 的 glassfish 上运行 webapps

java - JFilechooser 无法与选择按钮正常工作

java - 递归java问题

java - Belisha Beacon 程序中的 JButton 查询

java - 我应该将什么 Web 服务器与 NetBeans 一起使用?

java - 如何在 Java 中使用 JFileChooser 保存文件?

java - 更改 JFileChooser 的文本值

java - NoClassDefFound错误: org/apache/tiles/TilesApplicationContext Error with Spring Servlet