【问题标题】:How to Know if JFileChooser is null and if its null dont Update the database如何知道 JFileChooser 是否为 null 以及它是否为 null 不更新数据库
【发布时间】:2015-04-15 17:29:51
【问题描述】:

这是我的代码

    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。

【问题讨论】:

  • 在执行更新查询之前只需检查Null!!
  • 你能给我一个代码吗?

标签: java netbeans jfilechooser


【解决方案1】:

您可以像这样检查您的 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 编程的新手。非常感谢。
  • 没问题,但我强烈建议如果你想学习一些东西,请阅读教程,否则你会更经常遇到这些麻烦!
猜你喜欢
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多