【问题标题】:How do I store a picture in MySQL?如何在 MySQL 中存储图片?
【发布时间】:2010-12-28 16:35:34
【问题描述】:

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

【问题讨论】:

  • 更好的选择是将图像的物理路径存储在数据库中。

标签: java mysql database blob


【解决方案1】:

读取文件内容(BINARY) 并将其插入到 insert \ update MYSQL 查询中

谷歌中有很多例子:

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

【讨论】:

    【解决方案2】:

    您可能想查看以下示例:

    来自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'));
    

    【讨论】:

    • 我们可以使用简单的查询语言插入图片吗?
    • 是的,您可能想尝试使用LOAD_FILE() 函数:INSERT INTO mytbl (image_data) VALUES(LOAD_FILE('/tmp/myimage.png')); (freeopenbook.com/mysqlcookbook/mysqlckbk-CHP-17-SECT-7.html)
    • Karthik,什么不起作用?...LOAD_FILE() 方法?如果是,请确保该文件可由 mysql 读取,并确保您的 mysql 用户具有FILE 权限。
    • @Daniel : 如何检查我的 MySQl 是否具有文件权限,如果我没有权限,如何授予权限以及如何将图像文件存储在服务器主机中?
    • @Karthik:MySQL 错误跟踪器 bugs.mysql.com/bug.php?id=38403 存在问题,报告的行为与您遇到的相同。显然,一位用户通过停止 apparmor(这是一种类似 selinux 的安全服务)解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2013-03-24
    • 2020-06-25
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多