Blob and Clob data type : Blob Clob « Database « Java Tutorial






import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BlobClobEx {
  public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "yourName", "mypwd");

    Statement stmt = conn.createStatement();

    createBlobClobTables(stmt);

    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobClob VALUES(40,?,?)");

    File file = new File("blob.txt");
    FileInputStream fis = new FileInputStream(file);
    pstmt.setBinaryStream(1, fis, (int) file.length());

    file = new File("clob.txt");
    fis = new FileInputStream(file);
    pstmt.setAsciiStream(2, fis, (int) file.length());
    fis.close();

    pstmt.execute();

    ResultSet rs = stmt.executeQuery("SELECT * FROM BlobClob WHERE id = 40");
    rs.next();

    java.sql.Blob blob = rs.getBlob(2);
    java.sql.Clob clob = rs.getClob(3);

    byte blobVal[] = new byte[(int) blob.length()];
    InputStream blobIs = blob.getBinaryStream();
    blobIs.read(blobVal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bos.write(blobVal);
    blobIs.close();

    char clobVal[] = new char[(int) clob.length()];
    Reader r = clob.getCharacterStream();
    r.read(clobVal);
    StringWriter sw = new StringWriter();
    sw.write(clobVal);

    r.close();
    conn.close();
  }

  public static void createBlobClobTables(Statement stmt) throws Exception {
    String Sql = "CREATE TABLE BlobClob(Id NUMBER(3), b BLOB, c CLOB)";

    try {
      stmt.executeUpdate("DROP TABLE BlobClob");
    } catch (SQLException se) {
      if (se.getErrorCode() == 942)
        System.out.println("Error dropping BlobClob table:" + se.getMessage());
    }
    if (stmt.executeUpdate(Sql) == 0)
      System.out.println("BlobClob table created...");

  }
}








20.22.Blob Clob
20.22.1.Getting and Inserting Binary Data into an Database Table
20.22.2.Store BLOBs data into database
20.22.3.Read BLOBs data from database
20.22.4.Blob and Clob data type
20.22.5.Getting BLOB Data from a Database Table: how to retrieves bytes from a BLOB.
20.22.6.Store CLOBs data into database?
20.22.7.Read CLOBs data from database
20.22.8.Insert an Image
20.22.9.Retrieve an Image