`

【java】java读取图像文件存入oracle中blob字段源代码

 
阅读更多
最近因为要做点东西很少写文章了。
尤其是技术类的文章。
在网上看了很多关于Java对blob字段的操作。
自己也尝试着写了个,
自己也修改了部分。
代码写得很乱。

数据库:oracle 10G  XE
数据源驱动:jdbc12.jar
文件名:WriteBlob
数据库中建立一个为clobtest的表,内有两个字段,name (varchar2(20)),content(blob)。


package dbdriver;

/**
 * 2008-09-28
 * @author duduli
 * email: lxyzj2000@gmail.com
 */
import java.sql.*;
import java.io.*;
import oracle.sql.*;

public class WriteBlob {

    public static void main(String[] args) {
        try {
            String fName2 = "";
            String fileName = "E:\\jianxin.bmp";
//E盘下游个jianxin.bmp的图像文件
            File f = new File(fileName);
            String fName = f.getName();  
            int i = fName.lastIndexOf('.');   
            if (i > 0 && i < fName.length()-1){   
                   fName2 = fName.substring(0,i);   
                }   
            System.out.println(fName2);
//获得文件名,出去后缀的文件名。
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
            Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE", "system", "duduli   ");
            conn.setAutoCommit(false);
            BLOB blob = null;
            PreparedStatement pstmt = conn.prepareStatement("insert into blobtest(name,content) values(?,empty_blob())");
            pstmt.setString(1, fName2);
            pstmt.executeUpdate();
            pstmt.close();
            pstmt = conn.prepareStatement("select content from blobtest where name= ? for update");
            pstmt.setString(1, fName2);
            ResultSet rset = pstmt.executeQuery();
            if (rset.next()) {
                blob = (BLOB) rset.getBlob(1);
            }

            FileInputStream fin = new FileInputStream(f);
            System.out.println("file size = " + fin.available());
            pstmt = conn.prepareStatement("update blobtest set content=? where name=?");
            OutputStream out = blob.getBinaryOutputStream();
            byte[] data = new byte[(int) fin.available()];
            fin.read(data);
            out.write(data);
            fin.close();
            out.close();
            pstmt.setBlob(1, blob);
            pstmt.setString(2, fName2);
            pstmt.executeUpdate();
            pstmt.close();
            conn.commit();
            conn.close();
                } catch (SQLException e) {
                    System.err.println(e.getMessage());
                    e.printStackTrace();
                } catch (IOException e) {
                    System.err.println(e.getMessage());
                }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics