Upload Image into database with Java

In this article, I am going to describe how to upload images to an Oracle database using an java. below are steps for do this.


1. Create table which have a blob data type.
2. Write java program.


Let's see how to insert image into database.Here is the explanation


Create table using oracle database.


Create table image
(
   name varchar2(20),
   photo blob
);

Java Program



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

public class ImageWriter {

	static Connection connection = null;
	static CallableStatement pstat = null;
	static String connectionURL = null;

	public static void main(String[] args) {
		try{
		Class.forName("oracle connection class");
		connection = DriverManager.getConnection("connection url", "username", "password");

		PreparedStatement pstat = connection.prepareStatement("insert into image(name,photo) values(?,?)");

		FileInputStream fin = new FileInputStream("D:\\test.jpg");
		pstat.setString(1, "ABC");
		pstat.setBinaryStream(2, fin, fin.available());

		int result = pstat.executeUpdate();
		System.out.println(result + " Record Successfully Inserted");

		connection.close();

		}catch(Exception e){
			e.printStackTrace();
		}

	}

}


Result : 1 Record Successfully Inserted