在线咨询
QQ咨询
服务热线
服务热线:13125520620
TOP

使用Struts实现BLOB字段的存取-数据库

发布时间:2011-11-12 浏览:13731

  前天帮朋友忙写了一个有关ORACLE数据库中BLOB字段的存取,发现网上关于BLOB字段的操作没有很完整的例子,在此我将我写的程序完整的贴出来,还望朋友指教。

  DBUtil类用于数据库连接

public class DBUtil {

 public static String driverName = "oracle.jdbc.driver.OracleDriver";
 public static String urlName = "jdbc:oracle:thin:@oracle:1521:nio";
 public static String userName = "study";
 public static String password = "study";
 
 public static Connection getConnection(){
    Connection conn =null;
    try{
        Class.forName(driverName);
        conn = DriverManager.getConnection(urlName,userName,password);
   }
   catch(ClassNotFoundException e){
              System.err.println("Register driver error!");
              return null;
   }
  catch(SQLException e){
                   System.err.println("Get database connection error!");
                   return null;
   }
   return conn;
  }
}

//FileLoadForm是Struts中的ActionForm
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class FileLoadForm extends ActionForm {
 
private FormFile wordFile;

 /**
  * Method validate
  * @param mapping
  * @param request
  * @return ActionErrors
  */
 public ActionErrors validate(
  ActionMapping mapping,
  HttpServletRequest request) {
          return null;
 }

 /**
  * Method reset
  * @param mapping
  * @param request
  */
 public void reset(ActionMapping mapping, HttpServletRequest request) {

 }

 /**
  * @return 返回 wordFile。
  */
 public FormFile getWordFile() {
  return wordFile;
 }
 /**
  * @param wordFile 要设置的 wordFile。
  */
 public void setWordFile(FormFile wordFile) {
  this.wordFile = wordFile;
 }
}

//FileLoadAction主要实现业务逻辑,在此实现了BLOB字段的存取,如果逻辑很复杂可以使用一个辅助类来实现数据库操作。
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import java.io.*;
import java.sql.*;
public class FileLoadAction extends Action {

 // -------------------------------------------- Instance Variables

 // -------------------------------------- Methods

 /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse response) {
  FileLoadForm fileLoadForm = (FileLoadForm) form;
        FormFile wordFile = fileLoadForm.getWordFile();
        Connection conn = DBUtil.getConnection();
        try{
         conn.setAutoCommit(false);
         Statement stm = conn.createStatement();
         String sql = "select decode(max(blob_id),null,0,max(blob_id)+1) from db_blob";
         ResultSet rs = stm.executeQuery(sql);
         int id = 0;
         if(rs.next()){
          id = rs.getInt(1);
         }
         rs.close();     
         sql = "insert into db_blob(blob_id,blob_name,blob_body) values("+id+",'"+wordFile.getFileName()+"',empty_blob())";
         stm.executeUpdate(sql);
         sql = "select blob_body from db_blob where blob_id = "+id+" for update";
         rs = stm.executeQuery(sql);
         if(rs.next()){
              Blob blob = rs.getBlob(1);
              BufferedInputStream in = new BufferedInputStream(wordFile.getInputStream());
              BufferedOutputStream out = new BufferedOutputStream(((oracle.sql.BLOB)blob).getBinaryOutputStream());
              int buffer = 0;
              while((buffer = in.read()) != -1){
               out.write(buffer);
              }
              out.flush();
              out.close();
              in.close();
         }
            rs.close();
            stm.close();
            conn.commit();
            conn.close();
        }
        catch(Exception e){
         System.err.println("insert error!");
         try{
          conn.rollback();
             System.out.println("transaction rollback !");
         }catch(Exception exp){System.err.println("rollbak error!");}
         return mapping.getInputForward();
        }
        return mapping.findForward("success");
 }

 public static void main(String []args){
        Connection conn = DBUtil.getConnection();
        try{
         Statement stm = conn.createStatement();
         String sql = "select blob_body from db_blob where blob_id =0";
         ResultSet rs = stm.executeQuery(sql);
         if(rs.next()){
          Blob blob = rs.getBlob("blob_body");
          FileOutputStream fileOut = new FileOutputStream("e:\\test.doc");
              BufferedInputStream in = new BufferedInputStream(((oracle.sql.BLOB)blob).getBinaryStream());
              BufferedOutputStream out = new BufferedOutputStream(fileOut);
              int buffer = 0;
              while((buffer = in.read()) != -1){
               out.write(buffer);
              }
         }
            rs.close();
            stm.close();
            conn.close();
        }
        catch(Exception e){
         e.printStackTrace();
        }
 }
 
}
//当然还需要一个JSP
<%@ page language="java" contentType="text/html;charset=gb2312"%>
<%@ taglib uri="/struts-bean" prefix="bean" %>
<%@ taglib uri="/struts-html" prefix="html" %>
<%@ taglib uri="/struts-logic" prefix="logic" %>

<html:html locale="true">
  <head>
    <html:base />
       
    <title>fileload</title>

  </head>
 
  <body>
    <html:form action="fileLoad" method="post" enctype="multipart/form-data">
      <table>
        <tr>
          <td>file1:</td>
          <td><html:file property="wordFile"/></td>
        </tr>
        <tr>
          <td><html:submit /></td>
          <td><html:reset/></td>
        </tr>
      </table>
    </html:form>
  </body>
</html:html>

TAG
软件定制,软件开发,瀚森HANSEN
0
该内容对我有帮助