2015-09-13 116 views
1

我已阅读关于在数据库中存储图像是不实际的,所以我将图像路径存储在Mysql数据库中。我如何在我的程序中显示图像?每当我试图设置一个JLabel的图标,一个错误说“无法转换字符串图标,我该怎么办?从数据显示图像

try { 
    Class.forName("com.mysql.jdbc.Driver"); 
    Connection con = DriverManager.getConnection(
      "jdbc:mysql://localhost:3306/jose", "root", "josehaha"); 
    Statement stat = (Statement) con.createStatement(); 
    stat.executeQuery("select img_path from product where ID = 1;"); 
    ResultSet rs = stat.getResultSet(); 
    Object path = rs.getString("img_path"); 
    jLabel1.setIcon("'" + path + "'"); 
} catch (ClassNotFoundException | SQLException e) { 
    JOptionPane.showMessageDialog(this, e.getMessage()); 
} 
+0

考虑使用[预处理语句] (http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html)... – Reimeus

回答

1

setIcon需要一个Icon对象参数

String path = rs.getString("img_path"); 
.... 
jLabel1.setIcon(new ImageIcon(path)); 
+0

谢谢你,它修复了错误,但我有一个关于在mysql中存储图像路径的问题。数据类型varchar为此,并且我发现每当我保存图像路径时,它都会修剪所有文件分隔符(\\),并且在检索它时遇到新问题 –

+0

在猜测我会说有可能是一些字符逃逸,但它可能值得一个新的问题... – Reimeus

+0

正确的,无论如何谢谢。 –