【问题标题】:Insert image into MySQL将图像插入 MySQL
【发布时间】:2013-06-19 13:47:43
【问题描述】:

我正在使用 netbeans 和 mySQL 创建产品。单击按钮时,我使用文件选择器从用户那里获取图像,例如:

public void handle(ActionEvent event){
     FileChooser fileChooser = new FileChooser();

        //Set extension filter
        FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
        FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
        fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);

        //Show open file dialog
        File file = fileChooser.showOpenDialog(null);

        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            WritableImage image = SwingFXUtils.toFXImage(bufferedImage, null);
            myImageView.setImage(image);
        } catch (IOException ex) {
            Logger.getLogger(CreateProductUI.class.getName()).log(Level.SEVERE, null, ex);
        }
}

我使用下面的代码显示图像:

Image image = panel.getMyImageView().getImage();

在我尝试将图像插入数据库之前它工作正常。这是我的构造函数和创建方法:

public Product(String name,String desc,double price, int quantity,String datestr,Image image){
    this.name = name;
    this.desc = desc;
    this.price = price;
    this.quantity = quantity;
    this.datestr = datestr;
    this.image = image;
}

public boolean create(){
    boolean success = false;
    DBController db = new DBController();
    String dbQuery; 
    db.getConnection();     

    dbQuery = "INSERT INTO sm_product(productName,productDescription,productPrice,productQuantity,dateOfCreation,productStatus,productImage) VALUES ('" + name + "', '" + desc + "', " + price + ", " + quantity + ",'" + datestr + "', 'Available', '" + image + "')";

    if (db.updateRequest(dbQuery) == 1){
        success = true;
    }
    db.terminate();
    return success;
}

但是,图像存储为“javafx.scene.image.WritableImage@3a6e48b3”。我用相同的图像尝试了两次,但地址不同。我想知道我是否以错误的方式存储图像?我不确定是否可以使用 select SQL 语句检索图像,因为我还没有尝试过,但我认为它不起作用。

任何人都有更好的方法来解决它,因为存储在数据库中的图像非常奇怪,我认为这可能是错误的。

提前致谢。

更新部分

public void getConnection(){ 
    String url = ""; 
    try { 
        //url = "jdbc:mysql://172.20.133.227/test"; 
        url = "jdbc:mysql://localhost/amkcc"; 
        con = DriverManager.getConnection(url, "root", "root"); 
        System.out.println("Successfully connected to " + url+ "."); 
    } 
    catch (java.sql.SQLException e) { 
        System.out.println("Connection failed ->"+ url); 
        System.out.println(e); 
    } 
} 

【问题讨论】:

  • 要存储需要传递byte[] 作为参数的blob。您将需要弄清楚如何从现有代码中构建它
  • 什么是blob?还有如何使用一个字节[]
  • 如果你用一点谷歌,我相信你能找到答案。
  • @DevZer0 docs.oracle.com/javase/6/docs/technotes/guides/jdbc/blob.html。我找到了这个。但是,我还是迷路了

标签: java mysql netbeans filechooser


【解决方案1】:

如何使用 JDBC 在 MySQL 中保存图像的示例:

File image = new File("C:/image.jpg");
psmnt = connection.prepareStatement
  ("insert into save_image(name, city, image, Phone) "+ "values(?,?,?,?)");
psmnt.setString(1,"MyName");
psmnt.setString(2,"MyCity");
psmnt.setString(4,"123456");
FileInputStream fis = new FileInputStream(image);
psmnt.setBinaryStream(3, (InputStream)fis, (int)(image.length()));
int s = psmnt.executeUpdate();

你的方法应该是这样的:

public boolean create(){
 boolean success = false;
 try{
 DBController db = new DBController();
 String dbQuery; 
 db.getConnection();     

 dbQuery = "INSERT INTO sm_product(productName,productDescription,productPrice,productQuantity,dateOfCreation,productStatus,productImage) VALUES (?,?,?,?, ?, 'Available', ?)";

 PreparedStatement psmnt = db.getConnection().prepareStatement(dbQuery);
 psmnt.setString(1,name);
 psmnt.setString(2, desc);
 psmnt.setDouble(3, price);
 psmnt.setInt(4, quantity);
 psmnt.setString(5, dateStr);

 File imageFile = new File("test.png");
 RenderedImage renderedImage = SwingFXUtils.fromFXImage(image, null);
 ImageIO.write(renderedImage, "png", imageFile); //Change extension appropriately
 FileInputStream fis = new FileInputStream(imageFile);
 psmnt.setBinaryStream(3, (InputStream)fis, (int)(imageFile.length()));
 int s = psmnt.executeUpdate();

 //check the value of s and initialize success appropriately

 return success;
 }catch(Exception e) { e.printStackTrace(); }
   return false;

}

'DBController` 中的getConnection() 方法应该是这样的:

public Connection getConnection(){ 
            if(con != null) return con;
    String url = ""; 
    try { 
        //url = "jdbc:mysql://172.20.133.227/test"; 
        url = "jdbc:mysql://localhost/amkcc"; 
        con = DriverManager.getConnection(url, "root", "root"); 
        System.out.println("Successfully connected to " + url+ "."); 
                    return con;
    } 
    catch (java.sql.SQLException e) { 
        System.out.println("Connection failed ->"+ url); 
        System.out.println(e); 
    } 
            return null;
} 

【讨论】:

  • 但是我从用户输入中获取文件,所以我不知道图像的确切位置。
  • 顺便说一句,这不是我投反对票。我的票还不够。这是其他用户的。你的连接类是做什么的?谢谢
  • 是的,我没有意识到这一点。顺便说一句,connection 对象应该从您的DBController 类中检索,可能类似于db.getConnection()
  • 我得到了未报告的异常 SQLException;必须被捕获或声明为抛出错误消息。而且到处都是红线。我猜我的 DBController 出了点问题?
  • 你应该在 try-catch 块中包含一些东西。如果您在进一步学习之前了解异常,那就太好了。更新了代码。
猜你喜欢
  • 2015-11-03
  • 2021-02-17
  • 2013-01-16
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2015-02-20
  • 2017-10-17
相关资源
最近更新 更多