java - 从 DB 检索图像到 imageView

标签 java mysql sql javafx

数据库中有一张带有图像的表格。我希望在 ImageView 中显示图像,但是出现了问题并且出现了 SQLException。

 ConnectionHelper ch=new ConnectionHelper();
    ch.Connect();
    String q="SELECT IMG FROM img_ins";

    Statement st=ch.con.createStatement();
    ResultSet rs = st.executeQuery(q);

   InputStream is= rs.getBinaryStream("IMG");
    OutputStream os=new FileOutputStream(new File("img.jpg"));
    byte [] content= new byte[1024];
    int size=0;


        while ((size=is.read(content))!=-1){

            os.write(content, 0, size);
        }

    os.close();
    is.close();

    javafx.scene.image.Image image1=new Image("file:img.jpg", image.getFitWidth(), image.getFitHeight(), true, true);
    image.setImage(image1);
    image.setPreserveRatio(true);
}

最佳答案

来自 ResultSet 的文档(我的重点):

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row

因此您需要调用next()将光标指向每一行。假设表中最多有一行,或者您只对第一行感兴趣,您可以这样做

ConnectionHelper ch=new ConnectionHelper();
ch.Connect();
String q="SELECT IMG FROM img_ins";

Statement st=ch.con.createStatement();
ResultSet rs = st.executeQuery(q);

if (rs.next()) {
    InputStream is= rs.getBinaryStream("IMG");

    // instead of the next 9 lines, you could just do
    // javafx.scene.image.Image image1 = new Image(is);

    OutputStream os=new FileOutputStream(new File("img.jpg"));
    byte [] content= new byte[1024];
    int size=0;


        while ((size=is.read(content))!=-1){

            os.write(content, 0, size);
        }

    os.close();
    is.close();

    javafx.scene.image.Image image1=new Image("file:img.jpg", image.getFitWidth(), image.getFitHeight(), true, true);
    image.setImage(image1);
    image.setPreserveRatio(true);
}

但也要注意OP下面的评论。

关于java - 从 DB 检索图像到 imageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43984021/

相关文章:

java - docker OCI 运行时创建失败

mysql - 同一张表上的SQL嵌套查询

sql - LEFT JOIN 具有多个 AND 条件的两个表

java - 在自定义 View 中触摸和删除触摸时绘制圆圈

java - 无法通过对象输出流将对象从一个 http 处理程序发送到另一个

mysql - LEFT JOIN 操作上的 NULL 值

php - SQL:从表中选择列并比较+计数

sql - 当我阅读其他关于此的帖子时,我仍然看不出 GROUP BY 和 ORDER BY 在 SQL 中的区别。它是什么?

java - 如何在 NetBeans 中设置 Inno Setup 插件

mysql - 在mysql中,简单的连接查询需要很长时间才能执行