Save and Retrieve Image from MySql Database Using Java

Here you will get an example for save and retrieve image from MySql database using Java.

In development we generally use folders for managing images. But we can store images directly in database using BLOB (Binary Large Object) data type.

MySql has following blob types:

TINYBLOB: 255 bytes

BLOB: 64 KB

MEDIUMBLOB: 16 MB

LONGBLOB: 4 GB

Save and Retrieve Image from MySql Database Using Java

Depending upon requirement we can use any type. It is recommend no to use database for storing images with large size because it will increase the database size.

Below I have given an example of how to store and retrieve images from database. The description for table that I used is given below.

Table Details

Save and Retrieve Image from MySql Database Using Java

How to Save Image in Database

package com;

import java.sql.*;
import java.io.*;

public class DatabaseImageExample {
	public static void main(String args[]){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con=DriverManager.getConnection("jdbc:mysql://localhost/demo","root","root");
			
			File file=new File("E:\\image.png");
			FileInputStream fis=new FileInputStream(file);
			
			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();
		}
	}
}

Above example will take image from location E:\\image.png and save it into database table. Actually you can’t see the image directly in the table. You have to retrieve it from database and then save it to some location. Below example shows how you can do this.

How to Retrieve Image from Database

package com;

import java.io.*;
import java.sql.*;

public class DatabaseImageExample {
	public static void main(String args[]){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con=DriverManager.getConnection("jdbc:mysql://localhost/demo","root","root");
			
			File file=new File("E:\\image1.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();
			fos.close();
			con.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

Above example will fetch image from database and save it at location E:\\image1.png.

Comment below if you facing difficulty to understand above code.

Happy Coding!! 

🙂

 

🙂

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值