简体   繁体   English

从数据库中检索图像并显示在标签中

[英]Retrieve image from database and display in label

I am having one image named P100.jpg . 我有一张名为P100.jpg图像。 I am resizing it and it is converted into ZP100.png . 我正在调整其大小,并将其转换为ZP100.png I am storing it into database MySQL, by insert query. 我通过插入查询将其存储到数据库MySQL中。

    File imageFile = new File("F:\\POSTERS\\Roses\\ZP100.png");
    FileInputStream fis = new FileInputStream(imageFile);

    String insertImage = "insert into image values(?,?)";
    prestmt = con.prepareStatement(insertImage);
    prestmt.setInt(1,4);
    prestmt.setBinaryStream(2, fis, fis.available());
    result = prestmt.executeUpdate();

Now I want to retrieve that image and display on a form by assigning it to a label. 现在,我想检索该图像并通过将其分配给标签来显示在表单上。

    String selectImage = "select img from image";
    prestmt = con.prepareStatement(selectImage);

But it's giving me exception as 但这给了我例外

java.sql.SQLException: Can not issue executeUpdate() for SELECTs

For assigning image to a label I have: 为图像分配标签,我有:

    image.setText("ZP100.png"); 

I know, it cannot work. 我知道,这行不通。 Please help me to recode this. 请帮我重新编码。

First error must be at this: 第一个错误必须是这样的:

result = prestmt.executeUpdate();

I fear you have declared result with type ResultSet . 我担心您已使用ResultSet类型声明了result
And when you are assigning an int , the return type of executeUpdate() , to result 当您分配int ,返回类型executeUpdate() result
obviously an SQLException is raised. 显然会引发SQLException

Modify above statement like this: 像这样修改以上语句:

int insertResult = prestmt.executeUpdate();

And you should get a success on it. 而且您应该在此上取得成功。

Suggestion : 建议

prestmt.setBinaryStream( 2, fis, fis.available() ); prestmt.setBinaryStream(2, fisfis.available() );

Don't depend o available() method if you want to read content from a stream. 如果要从流中read内容, available()不要依赖available()方法。
It is just an estimate and won't guarantee you that you can read till the end of stream. 这只是一个估计 ,并不能保证您可以阅读到流结束为止。

Instead use the other signature of the setBinaryStream method like: 而是使用setBinaryStream方法的其他签名,例如:
setBinaryStream( int parameterIndex, InsputStream is )
Javadoc says, The data will be read from the stream as needed until end-of-file is reached. Javadoc说, The data will be read from the stream as needed until end-of-file is reached. , meaning you need not read it explicitly. ,这意味着您无需显式阅读它。
With the change, your statement would look like: 进行更改后,您的语句将如下所示:

prestmt.setBinaryStream( 2, fis ); prestmt.setBinaryStream(2,fis);


Image : 图片
I have not worked much on Java GUI and images. 我在Java GUI和图像上工作不多。
But can suggest you to refer to some solutions at: 但可以建议您在以下位置参考一些解决方案:

  1. Add Image to Button 将图像添加到按钮
  2. Label with Image 带有图像的标签

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM