如何在MySQL中存储图片? [英] How do I store a picture in MySQL?
本文介绍了如何在MySQL中存储图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在MySQL数据库中存储一个图像。我已经创建了一个具有BLOB数据类型的表,但现在如何将图像存储在此表中?
解决方案
查看以下示例:
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。驱动程序);
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 = 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服务器主机上,则可以使用 LOAD_FILE()
INSERT INTO MyPictures(照片)VALUES(LOAD_FILE)来自MySQL客户端的$ c>
命令:
< ('/tmp/photo.png'));
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?
解决方案
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:
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:
INSERT INTO MyPictures (photo) VALUES(LOAD_FILE('/tmp/photo.png'));
这篇关于如何在MySQL中存储图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文