Skip to content

Instantly share code, notes, and snippets.

@madan712
Created November 6, 2012 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save madan712/4024570 to your computer and use it in GitHub Desktop.
Save madan712/4024570 to your computer and use it in GitHub Desktop.
JDBC - how to retrive the files from blob storage
import java.io.FileOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SimpleBlobExample {
public static void main(String[] args) {
try {
Connection con;
Statement stat;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/schemaName", "username",
"password");
stat = con.createStatement();
String query = "select pic_id,pic_name,pic_file from blobtest;";
ResultSet rset = stat.executeQuery(query);
Blob blob = null;
while (rset.next()) {
System.out.println(rset.getString("pic_id") + " "
+ rset.getString("pic_name"));
blob = rset.getBlob("pic_file");
writeBlobFile(rset.getString("pic_name"), blob.getBytes(1,
(int) blob.length()));
}
stat.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Write byte array to a file using FileOutputStream
public static void writeBlobFile(String filename, byte[] data) {
try {
FileOutputStream fos = new FileOutputStream("C:/" + filename);
fos.write(data);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment