How to Convert Blob column to String in Java

How to Convert java.sql.Blob column datatype  to String in Java

 

Given below is the sample for all of you. Just sample exception handling is there and for production deployment code require modifications like cleaning up database connections and a proper exception handling.


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Blob;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class DBUtil{

    public void getEmployeeData(int employeeId){
        Connection databaseConn = getDBConnection();
        PreparedStatement pStmt = databaseConn.prepareCall("Select Employee_Summary from Employee where EmpID=?");
        pStmt.setInt(1, employeeId);
        ResultSet rs = pStmt.executeQuery();
        Blob blob = rs.getBlob("Employee_Summary");
       
        byte[] bdata = blob.getBytes(1, (int) blob.length());
        String empSummary = new String(bdata);
    }
   
 

    public Connection getDBConnection() {

        Properties properties = new Properties();
        Connection con = null;
        try {
            InputStream iStream = new BufferedInputStream(new FileInputStream("/home/application/db.properties"));
            properties.load(iStream);
            iStream.close();
            String driver = properties.getProperty("db.jdbcDriver");
            String dataSource = properties.getProperty("db.dataSource");
            String dbUserName = properties.getProperty("db.user");
            String dbPassword = properties.getProperty("db.password");
            try {
                Class.forName(driver);
                con = DriverManager.getConnection(dataSource, dbUserName,
                        dbPassword);
            } catch (ClassNotFoundException e) {
                LogManager.debug(DBUtil.class.getName(), " getConnection, ClassNotFoundException :" + e.getMessage());
            } catch (SQLException e) {
                LogManager.debug(DBUtil.class.getName(), " getConnection, SQLException :" + e.getMessage());
            }
        } catch (FileNotFoundException e) {
            LogManager.debug(DBUtil.class.getName(), " getConnection, FileNotFoundException :" + e.getMessage());
        } catch (IOException e) {
            LogManager.debug(DBUtil.class.getName(), " getConnection, IOException :" + e.getMessage());
        }
        return con;
    }
 

}

 

 

No comments:

Post a Comment