Wednesday, December 24, 2008

How to get BLOB data type using Java

How to get Blob data type using Java?

You can use the following code to get Blob data type using Java programming:


public Image getPhoto()
{
ImageIcon dPhoto = null;
// my open connection function
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/PTIK", "sa", "umar");

ResultSet rs = con.createStatement().executeQuery("SELECT PHOTO FROM KARYAWAN");
if (rs.next())
{
Blob image = rs.getBlob("PHOTO");

int panjang = (int)image.length();
// set read buffer size
byte[] blobValue = new byte[panjang];

// setup the streams
InputStream input = image.getBinaryStream();
input.read(blobValue);

ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write(blobValue);

byte[] hasilPhoto = output.toByteArray();

// load final buffer
dPhoto = new ImageIcon(hasilPhoto);
}
con.close();
}
catch (Exception exc)
{
exc.printStackTrace();
}
return (dPhoto.getImage());
}


Now you can display Image data type using JButton, JLabel, ...