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
How do I store a picture in MySQL?
提问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:
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
read the content of the file (BINARY) and insert it in insert \ update MYSQL query
读取文件(BINARY)的内容并将其插入到insert\update MYSQL查询中
a lot of example in google :
谷歌中有很多例子:
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertpicturetoMySQL.htm
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertpicturetoMySQL.htm
http://www.roseindia.net/jdbc/save_image.shtml
http://www.roseindia.net/jdbc/save_image.shtml

