2009-12-21 68 views
7

我想將圖像存儲在MySQL數據庫中。我已經創建了一個BLOB數據類型的表,但現在如何將圖像存儲在此表中?如何在MySQL中存儲圖片?

+4

更好的選項可以存儲圖像在數據庫中的物理路徑。 – 2009-12-21 10:41:03

回答

11

你可能想看看下面的例子E:

java2s.com: Insert picture to MySQL

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 

public class InsertPictureToMySql { 
    public static void main(String[] args) throws Exception, IOException, SQLException { 
    Class.forName("org.gjt.mm.mysql.Driver"); 
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root"); 
    String INSERT_PICTURE = "INSERT INTO MyPictures (photo) VALUES (?)"; 

    FileInputStream fis = null; 
    PreparedStatement ps = null; 
    try { 
     conn.setAutoCommit(false); 
     File file = new File("/tmp/photo.png"); 
     fis = new FileInputStream(file); 
     ps = conn.prepareStatement(INSERT_PICTURE); 
     ps.setBinaryStream(1, fis, (int) file.length()); 
     ps.executeUpdate(); 
     conn.commit(); 
    } finally { 
     ps.close(); 
     fis.close(); 
    } 
    } 
} 

MySQL表:

CREATE TABLE MyPictures (
    photo BLOB 
); 

如果圖像位於你的MySQL服務器主機上,你可以從一個MySQL客戶使用LOAD_FILE()命令:

INSERT INTO MyPictures (photo) VALUES(LOAD_FILE('/tmp/photo.png')); 
+0

我們可以使用簡單的查詢語言插入圖像嗎? – 2009-12-21 09:51:00

+3

是的,你可能想嘗試使用'LOAD_FILE()'函數:'INSERT INTO mytbl(image_data)VALUES(LOAD_FILE('/ tmp/myimage.png'));'(http://www.freeopenbook.com /mysqlcookbook/mysqlckbk-CHP-17-SECT-7.html) – 2009-12-21 09:56:13

+0

不工作的夥伴.... – 2009-12-21 10:14:26