2015-09-13 114 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

正確的,無論如何謝謝。 –