日期:2014-05-18 浏览次数:20719 次
import java.io.*; import java.sql.*; import javax.swing.*; /* -- 测试表 环境:oracle 9i下的 create table TestImage( img_id int primary key, img_content blob ) */ public class BlobTestForOracle { private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:oratest"; private static final String DB_USER = "test"; private static final String DB_PASSWORD = "password"; public BlobTestForOracle(){ try { Class.forName(DB_DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 另村为... * * */ public String chooseFileSave(String title,String fileName){ JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(new File(fileName)); chooser.setDialogTitle(title); int rnt = chooser.showSaveDialog(null); if(rnt == JFileChooser.APPROVE_OPTION){ return chooser.getSelectedFile().getAbsolutePath(); }else{ return ""; } } /** * 打开... * * */ public String chooseFileOpen(String title,String fileName){ JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(new File(fileName)); chooser.setDialogTitle(title); int rnt = chooser.showOpenDialog(null); if(rnt == JFileChooser.APPROVE_OPTION){ return chooser.getSelectedFile().getAbsolutePath(); }else{ return ""; } } /** * 写入blob * */ public void writeFileToDatabaseByRid(String fileName,int rid){ BufferedInputStream bis = null; Connection conn = null; PreparedStatement pstmt = null; String strSQL = null; File file = null; int size = 0; try{ strSQL = "INSERT INTO TestImage(img_id,img_content) VALUES(?,?)"; conn = DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWORD); pstmt = conn.prepareStatement(strSQL); fileName = this.chooseFileOpen("请选择一个文件",fileName); file = new File(fileName); if(! file.exists()){ System.out.println(file.getAbsolutePath()); System.out.println("文件貌似不存在!"); return; } else if(file.length() > 50 * 1024 * 1024){ // 限制一下文件大小 System.out.println("文件是不是太大鸟? " + file.length()); return; } size = (int)file.length(); bis = new BufferedInputStream(new FileInputStream(file)); pstmt.setInt(1, rid); pstmt.setBinaryStream(2,bis,size); int effect = pstmt.executeUpdate(); if(effect == 1){ System.out.println("写入ok!" + file.getAbsolutePath()); } else{ System.out.println("写入failed!"); } bis.close(); }catch(IOException ioe){ ioe.printStackTrace(); }catch(SQLException sqle){ sqle.printStackTrace(); }finally{ if(pstmt != null){ try { pstmt.close();