January 1, 2012

JDBC Code to insert an image in a BLOB column

0) Complete the first 5 steps in the JDBC code example at the link here

1) Create a new table in the database using the following CREATE TABLE command

create table MyImages (
   name VARCHAR(1000),
   image BLOB

2) Add the image file to the src folder of the Java Project/Application

3) Create a Java class - JdbcBlobExample.java - to the src folder of the Java Project/Application

package info.icontraining.jdbc;

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

public class JdbcBlobExample {
   public static void main(String[] args) throws Exception, IOException, SQLException {
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");

      FileInputStream fis = null;
      PreparedStatement pstmt = null;
      try {
         File file = new File("src/icon-training.jpg");
         fis = new FileInputStream(file);
         pstmt = conn.prepareStatement("insert into MyImages(name, image) values (?, ?)");
         pstmt.setString(1, "Icon Training Logo");
         pstmt.setBinaryStream(2, fis, (int) file.length());
      } catch (Exception e) {
      } finally {

4) Run the code as a standalone Java Application

No comments:

Post a Comment