【问题标题】:Retrieve image from database and display in label从数据库中检索图像并显示在标签中
【发布时间】:2012-05-25 07:25:20
【问题描述】:

我有一张名为P100.jpg 的图片。我正在调整它的大小并将其转换为ZP100.png。我通过插入查询将它存储到数据库 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();

现在我想检索该图像并通过将其分配给标签来显示在表单上。

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

但它给了我例外

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

为了将图像分配给我拥有的标签:

    image.setText("ZP100.png"); 

我知道,这行不通。请帮我重新编码。

【问题讨论】:

  • 任何人都可以帮助我......

标签: java mysql sql database sqlexception


【解决方案1】:

第一个错误一定是在这个:

result = prestmt.executeUpdate();

我担心你已经用ResultSet 类型声明了result
当您将intexecuteUpdate() 的返回类型)分配给result
显然一个SQLException 被提出。

修改上面的语句如下:

int insertResult = prestmt.executeUpdate();

你应该在这方面取得成功。

建议

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

如果您想read 流中的内容,请不要依赖 oavailable() 方法。
这只是一个估计,并不能保证您可以阅读直到流结束。

改为使用setBinaryStream 方法的另一个签名,例如:
setBinaryStream( int parameterIndex, InsputStream is )
Javadoc 说,The data will be read from the stream as needed until end-of-file is reached.,这意味着你不需要明确地阅读它。
更改后,您的声明将如下所示:

prestmt.setBinaryStream(2, fis);


图片
我在 Java GUI 和图像方面工作不多。
但可以建议您参考一些解决方案:

  1. Add Image to Button
  2. Label with Image

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2015-10-08
    相关资源
    最近更新 更多