2016-12-28 21 views
3

爲了執行任務,我必須將圖像作爲Blob格式存儲到MySQL中(儘管存儲圖像路徑會更好,更理想在數據庫中並將圖像保存在localcopy中的文件夾中)。如何着手將圖像以Blob格式保存到Java中的Java

到目前爲止,我已經研究,但沒有找到任何答案,可以幫助我,這是我迄今所做

不久,單擊按鈕,這將被解僱:

empdao.insertImage(fis); 

圖像填充另一個甚至聽者這樣的:

static FileInputStream fis = null; 
static String path = null; 
path = filechooser.getSelectedFile().getAbsolutePath(); 
File image = new File(path); 
fis = new FileInputStream (image); 

這下面的代碼需要將它添加到數據庫中的護理。

public void insertImage(FileInputStream fis) throws SQLException { 



Connection c = getConnection();  

    String query = "INSERT INTO Picture (picture) VALUES (?)"; 

    System.out.println(query); 

    PreparedStatement pstmt = c.prepareStatement(query); 

    pstmt.setBinaryStream(1, fis); 

    pstmt.executeUpdate(); 

    c.close(); 
} 

但問題是,我需要它,將其轉換爲一個blob,我不知道如何,有人可以幫助我或者指導我如何去選擇的圖像存儲爲一個BLOB字段成MySQL的。

當前它將它添加到數據庫中時,我在圖片列中獲得了java.io文件輸入。

+0

http://stackoverflow.com/a/41235395/267540 – e4c5

回答

3

假設您在MySQL中有一個表my_picures,其中id INT PRIMARY KEY,name VARCHAR(255),photo BLOB

然後你可以用下面的Java代碼中插入一個新的圖片作爲BLOB

public class InsertPictureAsBlob { 
    public static void main(String[] args) throws Exception, IOException, SQLException { 
     Class.forName("com.mysql.jdbc.Driver"); 
     Connection conn = DriverManager 
      .getConnection("jdbc:mysql://localhost/databaseName", "username", "password"); 
     String INSERT_PICTURE = "INSERT INTO my_picures(id, name, photo) VALUES (?, ?, ?)"; 

     conn.setAutoCommit(false); 
     File file = new File("myPhoto.png"); 
     try (FileInputStream fis = new FileInputStream(file); 
        PreparedStatement ps = conn.prepareStatement(INSERT_PICTURE)) { 
      ps.setString(1, "001"); 
      ps.setString(2, "name"); 
      ps.setBinaryStream(3, fis, (int) file.length()); 
      ps.executeUpdate(); 
      conn.commit(); 
     } 
    } 
} 
+0

我已經做出了修改,但是它仍然不會將圖像添加到數據庫中,即使使用PreparedStatement –

+0

謝謝它,因爲我忘記了添加大小位 –

+0

歡迎您。 – DimaSan

2

1)首先你會想要確保你有你的MySQL架構與創建的表定義了BLOB列類型(BLOB,MEDIUMBLOB,LONGBLOB)。查看MySQL中可用的BLOB列類型並選擇適當的大小。

2)您將要從使用語句切換到PreparedStatement。

String query = "INSERT INTO Pictures (Picture) VALUES (?)"; 
PreparedStatement pstmt = conn.prepareStatement(query); 

3)你正在傳遞一個FileInputStream你的方法,所以你只需要使用上PreparedStatement的setBinaryStream方法。

pstmt.setBinaryStream(1, fis); 

4)然後在PreparedStatement上執行executeUpdate()。

pstmt.executeUpdate(); 

利用異常處理你在你的原始代碼和你在你原來的代碼是什麼執行的對象適當的清理(數據庫連接,準備語句),相似。

+0

無論如何,我可以使用常規語句來代替PreparedStatement,因爲它的任務和我必須遵循規範? –

+0

@ jomin_george94上面的代碼是你應該怎麼做的,你現在的代碼是什麼,而且我不能放任何其他方式,不安全的垃圾,而不是用Java編寫好的數據庫訪問代碼。我不確定你的意思是「必須遵循規範」,但規範通常會描述需要完成的工作,而不是應該如何實施。 –

+0

當我按照你的建議,我得到NullPointerException並且在這一行失敗: –