readblobfromdb.java

来自「JAVA读取JPEG图象」· Java 代码 · 共 102 行

JAVA
102
字号
//package jdbcblob;import javax.swing.*;import java.io.*;import java.sql.*;/** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * @author unascribed * @version 1.0 */public class ReadBlobFromDb {  Connection conn;  Statement stmt;  ResultSet rs;  int bufferSize;  public ReadBlobFromDb() throws SQLException,ClassNotFoundException {    Class.forName("oracle.jdbc.driver.OracleDriver") ;    String sourceURL="jdbc:oracle:thin:@localhost:1521:cnaloral";    String user="system";    String password="cnaloral8";    conn=DriverManager.getConnection(sourceURL,user,password) ;    stmt=conn.createStatement() ;  }  public void readFromDb(){    String pathname,name;    int amount=0;    BufferedOutputStream out=null;    InputStream in=null;    JFileChooser chooser=new JFileChooser();    int returnVal=chooser.showOpenDialog(null) ;    if (returnVal==JFileChooser.APPROVE_OPTION) {      pathname=chooser.getSelectedFile() .getAbsolutePath();      name=chooser.getSelectedFile() .getName() ;      chooser=null;    }    else {      System.out.println("No file selected for writing data from DB!");      System.out.println("Program terminating!");      return;    };    try {      rs=stmt.executeQuery("select data from media where trim(name)='"+name.trim()+"'") ;      if (rs.next()) {        Blob blob=rs.getBlob(1) ;        in=blob.getBinaryStream() ;        bufferSize=((oracle.sql.BLOB )blob).getBufferSize() ;        out=new BufferedOutputStream(new FileOutputStream(pathname),(int)bufferSize);        byte[] b=new byte[(int)bufferSize];        int count=in.read(b,0,(int)bufferSize);        while (count!=-1) {          out.write(b,0,count);          amount+=count;          System.out.println("Processed "+amount+" bytes.");          count=in.read(b,0,(int)bufferSize);        };        System.out.println("Processed "+amount+"bytes.Finished!");        out.close();        out=null;        in.close();        in=null;      }      else {        System.out.println("The name "+name+" was not found in the media table!");      };    }    catch (Exception ex) { ex.printStackTrace() ;    }    finally {      if (out!=null) try{out.close() ;} catch(Exception ignored){};      if (in!=null) try{in.close() ;} catch(Exception ignored){};    }  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?