Java by API/java.sql/Blob

Материал из Java эксперт
Перейти к: навигация, поиск

Blob: getBinaryStream()

   <source lang="java">

import java.io.ObjectInputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.ImageIcon; public class Main {

 public static void main(String[] args) throws Exception {
   ImageIcon image;
   Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/c:\\employee");
   Statement s = con.createStatement();
   ResultSet rs = s.executeQuery("select photo from employee where name = "Duke"");
   if (rs.next()) {
     Blob photo = rs.getBlob(1);
     ObjectInputStream ois = null;
     ois = new ObjectInputStream(photo.getBinaryStream());
     image = (ImageIcon) ois.readObject();
   } 
   s.close();
 }

}

 </source>
   
  
 
  



Blob: getBytes(long pos, int length)

   <source lang="java">

import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.swing.JPanel; public class BlobSelect extends JPanel {

 public static void main(String args[]) throws Exception {
   Connection conn = null;
   byte[] data = getBLOB(01, conn);
 }
 public static byte[] getBLOB(int id, Connection conn) throws Exception {
   ResultSet rs = null;
   PreparedStatement pstmt = null;
   String query = "SELECT photo FROM MyPictures WHERE id = ?";
   try {
     pstmt = conn.prepareStatement(query);
     pstmt.setInt(1, id);
     rs = pstmt.executeQuery();
     rs.next();
     Blob blob = rs.getBlob("photo");
     // materialize BLOB onto client
     return blob.getBytes(1, (int) blob.length());
   } finally {
     rs.close();
     pstmt.close();
     conn.close();
   }
 }

}


 </source>
   
  
 
  



Blob: length()

   <source lang="java">

      

import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class Main {

 public static void main(String args[]) throws Exception {
   Connection conn = null;
   byte[] data = getBLOB(01, conn);
 }
 public static byte[] getBLOB(int id, Connection conn) throws Exception {
   ResultSet rs = null;
   PreparedStatement pstmt = null;
   String query = "SELECT photo FROM MyPictures WHERE id = ?";
   try {
     pstmt = conn.prepareStatement(query);
     pstmt.setInt(1, id);
     rs = pstmt.executeQuery();
     rs.next();
     Blob blob = rs.getBlob("photo");
     // materialize BLOB onto client
     return blob.getBytes(1, (int) blob.length());
   } finally {
     rs.close();
     pstmt.close();
     conn.close();
   }
 }

}

 </source>