我想将图像存储在MySQL数据库中。我创建了一个具有BLOB数据类型的表,但现在如何将图像存储在此表中?
答案 0 :(得分:10)
您可能需要查看以下示例:
来自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'));
答案 1 :(得分:5)
阅读文件内容(BINARY) 并将其插入insert \ update MYSQL查询
谷歌的很多例子:
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertpicturetoMySQL.htm