import java.sql.*;
import java.io.*;
public class InsertImage
{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
PreparedStatement ps = con.prepareStatement("insert into imgtable values(?,?)");
ps.setString(1, "TechSarvam");
FileInputStream fin = new FileInputStream("d:\\g.jpg");
ps.setBinaryStream(2, fin, fin.available());
int i = ps.executeUpdate();
System.out.println(i + " records affected");
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Step-by-Step Breakdown:
1. Importing Required Classes:
import java.sql.*;
import java.io.*;
The java.sql package provides classes for database operations, while the java.io package provides classes to handle file operations (like FileInputStream).
2. Class Declaration:
public class InsertImage {
This declares the class InsertImage that holds the program’s logic.
3. Main Method:
public static void main(String[] args) {
This is the program entry point: main method. This method gets executed when the program is run.
4. Try-Catch Block for Error Handling:
There is a try-catch block in the code. For any reason, if there was an error due to database connectivity or file read or SQL execution that had been caught at the catch and printed.
5. Loading the Oracle JDBC Driver:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
The class class.forName() loads the Oracle JDBC driver: oracle.jdbc.driver.OracleDriver, which is a must because otherwise, there’s no possibility to connect to the Oracle database.
6. Opening the Database Connection:
Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”, “system”, “oracle”);
The line code above for establishing a connection to an Oracle database uses the statement,
DriverManager.getConnection().
- Connection URL: jdbc:oracle:thin:@localhost:1521:xe identifies Oracle Database locally (localhost) located on the specified port (1521), the name of which is oracle, but XE represents its instance that can also be an oracle XE/express edition
- User-name : system and password : oracle is passed
7. Writing the PreparedStatement to insert values.
PreparedStatement ps = con.prepareStatement(“insert into imgtable values(?,?)”);
A PreparedStatement object is made for the SQL statement insert into imgtable values(?,?) where? is placeholder for what needs to be inserted.
It also assumes the following about imgtable table at least two columns.
1. One column in order to keep a name for an image such as VARCHAR data type.
2. A column for holding binary version of image like BLOB data type.
8. Passing the String Parameter (Image Name):
ps.setString(1, “TechSarvam”);
ps.setString(1, “TechSarvam”) assigns the string “TechSarvam” to the first parameter holder (?) which may contain the name or description of the image.
9. Reading the Image File Using FileInputStream:
FileInputStream fin = new FileInputStream(“d:\\\g.jpg”);
- FileInputStream fin = new FileInputStream(“d:////g.jpg”) declares the FileInputStream to read the image file at “d:////g.jpg”
- the path d:////g.jpg should be legitimate and refer to an actual picture file on your computer.
10. Setting Binary Data (the Image) for PreparedStatement
ps.setBinaryStream(2, fin, fin.available());
- ps.setBinaryStream(2, fin, fin.available()) streams the binary data of the image file into the second placeholder.
- fin.available() returns the size of the file in bytes, which is passed as the third argument to the setBinaryStream() method.
- This way the data of type binary is transmitted as a stream which is really ideal for the images as large in size
11. Updating Execution
int i = ps.executeUpdate();
- This call will execute the insert query so that image data gets inserted to the database table.
- The method will return the count of rows impacted by the execution of the query. The number of rows is assigned to variable i. It should generally return 1 since the query was an insert, so a single record is being successfully added.
12. Output Statement:
System.out.println(i + ” records affected”);
The program outputs the number of records affected by the query. This is basically the number of rows inserted into the table; this will print 1 if the record was successfully added to the database.
13. Closing Database Connection:
con.close();
close() closes the database connection freeing up the used resources by that connection.
14. Handling Exceptions:
} catch (Exception e) {
e.printStackTrace();
}
If any exception occurs during the execution (such as FileNotFoundException, SQLException, etc.), it is caught in the catch block and the stack trace of the exception is printed.
Database Setup:
For this program to be effective, the following should be in place:
1. Table Structure:
- The imgtable table must already exist in the Oracle database with appropriate columns. For example:
sql
CREATE TABLE imgtable (
name VARCHAR2(100),
image BLOB
);
- The first column name stores the name or description of the image (e.g., VARCHAR type), and the second column image stores the binary data (e.g., BLOB type).
2. Image File:
Ensure the image file g.jpg exists at the specified path (d:\\g.jpg), or change the path to an existing image file on your system.
Assuming that the image table is already created and the image file g.jpg is present at the given path, the output will be as follows:
1 records affected
This message means that one record (image and its name) has been inserted into the database successfully.
Possible Errors/Issues:
1. File Not Found:
If the file g.jpg does not exist at the specified path, then the program will throw a FileNotFoundException.
2. SQL Exception:
If the database connection is somehow faulty (for example, incorrect credentials or database not running), then a SQLException will be thrown.
3. Oracle Driver Missing:
In case the Oracle JDBC driver is not installed or configured properly, the program will throw a ClassNotFoundException at the time of loading the driver.