java – 如何在MySQL中存储图片?

前端之家收集整理的这篇文章主要介绍了java – 如何在MySQL中存储图片?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将图像存储在 MySQL数据库中.我创建了一个具有BLOB数据类型的表,但现在如何将图像存储在此表中?

解决方法

您可能需要查看以下示例:

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'));
原文链接:https://www.f2er.com/java/127948.html

猜你在找的Java相关文章