[英]How to retrieve image file from database using java
我可以将图像文件存储到数据库中,但是如何将图像作为文件获取并使用 java 进行预览,就像 quikr 图像上传
以下代码将图像存储和检索到 MySql DB。
将图像存储到数据库中
public static void main(String args[]){
try{
// DB connection
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/your db name","root","root");
File file=new File("E:\\sample_image.png");
FileInputStream fis=new FileInputStream(file);
//Insert image into db
PreparedStatement ps=con.prepareStatement("insert into image_table (name,image) values(?,?)");
ps.setString(1,"image 1");
ps.setBinaryStream(2,fis,(int)file.length());
ps.executeUpdate();
ps.close();
fis.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
将图像检索到数据库中
下面的代码将从数据库中检索图像并将其保存在@ location "E:\\sample_image.png"。
public static void main(String args[]){
try{
// DB connection
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/your db name","root","root");
File file=new File("E:\\sample_image.png");
FileOutputStream fos=new FileOutputStream(file);
byte b[];
Blob blob;
PreparedStatement ps=con.prepareStatement("select * from image_table");
ResultSet rs=ps.executeQuery();
while(rs.next()){
blob=rs.getBlob("image");
b=blob.getBytes(1,(int)blob.length());
fos.write(b);
}
ps.close();
fis.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.