How do I store a picture in MySQL?

对着背影说爱祢 提交于 2019-12-04 12:01:20

问题


I want to store an image in a MySQL database. I have created a table with a BLOB datatype, but now how do I store the image in this table?


回答1:


You may want to check out the following example:

From 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 Table:

CREATE TABLE MyPictures (
   photo  BLOB
);

If the image is located on your MySQL server host, you could use the LOAD_FILE() command from a MySQL client:

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



回答2:


read the content of the file (BINARY) and insert it in insert \ update MYSQL query

a lot of example in google :

http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertpicturetoMySQL.htm

http://www.roseindia.net/jdbc/save_image.shtml

http://www.jguru.com/faq/view.jsp?EID=1278882



来源:https://stackoverflow.com/questions/1939162/how-do-i-store-a-picture-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!