Oracle 文件字段(Blob)

package com;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;


public class DBConnection {
	private static Connection con = null;
	public static synchronized  Connection getConnection() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); 
			con = DriverManager.getConnection(
					" jdbc:oracle:thin:@localhost:1521:ORCL", "scott", "tiger");
	
			return con;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
}
 package com; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import oracle.jdbc.OracleConnection; import oracle.jdbc.OracleResultSet; import oracle.jdbc.driver.OraclePreparedStatement; public class TestBlog { private static OracleResultSet ors=null;//**这里rs一定要用Oracle提供的 private static OraclePreparedStatement opst=null;//**PreparedStatement用 private static OracleConnection con=null; public static void read_out(String toPath,String keyName) throws Exception{ con=(OracleConnection)DBConnection.getConnection(); FileOutputStream fout=null; File file=new File(toPath); fout=new FileOutputStream(file); byte b[]=null; String search="select name, IMAGE from test where name=? for update"; opst=(OraclePreparedStatement)con.prepareStatement(search); opst.setString(1,keyName); ors=(OracleResultSet)opst.executeQuery(); if(ors.next()){ System.out.println(ors.getString(1)); oracle.sql.BLOB blob=ors.getBLOB(2); System.out.println(blob.length()); b=blob.getBytes(1,(int) blob.length());/**从BLOB取出字节流数据*/ } fout.write(b,0,b.length); fout.close(); System.out.println("out write is ok....."); ors.close(); con.close(); } public static void write_in(String filePath) throws Exception{ con=(OracleConnection)DBConnection.getConnection(); String insert = "insert into test values (?,?,EMPTY_BLOB())"; byte write[]=null; FileInputStream fin=null; File file=new java.io.File(filePath); fin=new FileInputStream(file); int flength=(int)file.length();//**读入文件的字节长度 write=new byte[flength]; int n=0; n=fin.read(write, 0, flength-1); /* * 该方法效率十分 低下 * for(int i=0;i<flength;i++){ n=fin.read(write,i,flength-i); System.out.println(i); }*/ fin.close(); opst=(OraclePreparedStatement)con.prepareStatement(insert); opst.setInt(1,7); opst.setString(2,file.getName()); int up=opst.executeUpdate(); opst.clearParameters(); String search="select IMAGE from test where name=? for update"; opst=(OraclePreparedStatement)con.prepareStatement(search); opst.setString(1,file.getName()); ors=(OracleResultSet)opst.executeQuery(); if(ors.next()){ oracle.sql.BLOB blob=ors.getBLOB(1);//**得到BLOB字段*//* int j=blob.putBytes(1,write);//**将字节数组写入BLOB字段*//* System.out.println("j==="+j); } ors.close(); con.close(); System.out.println("insert into ok"); } public static void main(String[] args) throws Exception { String filePath = "e:\\test.jpg"; write_in(filePath); //read_out(filePath, "test.docx"); } }

 

你可能感兴趣的:(java,oracle,sql,jdbc,J#)