java 如何在 MySQL 中存储图片?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1939162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:37:18  来源:igfitidea点击:

How do I store a picture in MySQL?

javamysqldatabaseblob

提问by Karthik.m

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?

我想在 MySQL 数据库中存储图像。我已经创建了一个带有 BLOB 数据类型的表,但现在如何将图像存储在该表中?

回答by Daniel Vassallo

You may want to check out the following example:

您可能想查看以下示例:

From java2s.com: Insert picture to MySQL:

来自java2s.com:将图片插入到 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:

MySQL表:

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:

如果映像位于 MySQL 服务器主机上,则可以使用LOAD_FILE()MySQL 客户端中的命令:

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

回答by Haim Evgi