2009-12-21 6 views
7

Tôi muốn lưu trữ một hình ảnh trong cơ sở dữ liệu MySQL. Tôi đã tạo một bảng với một kiểu dữ liệu BLOB, nhưng bây giờ làm cách nào để lưu trữ hình ảnh trong bảng này?Làm cách nào để lưu trữ hình ảnh trong MySQL?

+4

Tùy chọn tốt hơn có thể lưu trữ đường dẫn vật lý của hình ảnh trong DB. –

Trả lời

11

Bạn có thể muốn xem bài kiểm tra sau e:

Từ 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 Bảng:

CREATE TABLE MyPictures (
    photo BLOB 
); 

Nếu hình ảnh nằm trên máy chủ máy chủ MySQL của bạn, bạn có thể sử dụng lệnh LOAD_FILE() từ một khách hàng MySQL:

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

Chúng tôi có thể chèn hình ảnh bằng ngôn ngữ truy vấn đơn giản không? –

+3

Có, bạn có thể thử sử dụng hàm 'LOAD_FILE()': 'INSERT INTO mytbl (image_data) VALUES (LOAD_FILE ('/ tmp/myimage.png'));' (http://www.freeopenbook.com) /mysqlcookbook/mysqlckbk-CHP-17-SECT-7.html) –

+0

Bạn đời không làm việc của nó .... –