Java向数据库orcale中类型为Blob字段赋值

将图片以流的形式存入到 blob类型的字段中:

第一步: 获取文件输入流 (获取方式有很多种)

	            DiskFileItemFactory fac = new DiskFileItemFactory();      
	            ServletFileUpload upload = new ServletFileUpload(fac); 
	             upload.setHeaderEncoding("UTF-8");  
	             // 获取多个上传文件      
	            List fileList = fileList = upload.parseRequest(request);      
	            Iterator it = fileList.iterator(); 
	            while (it.hasNext()) {      
	                Object obit = it.next();    
	                if(obit instanceof DiskFileItem){    
	                    //System.out.println("----------");    
	                    DiskFileItem item = (DiskFileItem) obit;  
	             BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流
	            .
	            .
	            .
	            }

第二步:将输入流转换为 buye [] 数组

		//获取到 输入流
		BufferedInputStream in = new BufferedInputStream(item.getInputStream());
		byte[] data = IOUtil.toByteArray(in);//方法内容在下方
	public static byte[] toByteArray(InputStream in) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream out=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024*4];
        int n=0;
        try {
			while ( (n=in.read(buffer)) !=-1) {
			    out.write(buffer,0,n);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
        return out.toByteArray();
	}

第三步 : 执行数据库操作

String sql = "insert into tableName (id,filename,empty_blob()) value(1,‘身份证’,empty_blob());

empty_blob() 先执行一条空数据,以 empty_blob() 赋值于 类型为 blob字段

 //sql为insert语句 
 //tableid 为表id值
 //data 为文件流
IOUtil.toBlobByTableData(sql, tableid, data);
public static void toBlobByTableData(String insertsql,int tableid,byte [] data) throws Exception{
		
		//加载驱动
		   Class.forName("oracle.jdbc.driver.OracleDriver");
		   String url="jdbc:oracle:thin:@xxx:1521:orcl";
		   Connection con=DriverManager.getConnection(url,"root","root");
		   con.setAutoCommit(false);  //把默认提交关闭,即开启了JDBC连接事务
		
		    Statement st = con.createStatement();   
		    //插入一个空对象empty_blob()   
		    st.executeUpdate(insertsql);   
		    //锁定数据行进行更新,注意“for update”语句   
		    ResultSet rs = st.executeQuery("select FPMSLT from MAPBUSIRECFILPHOTO where ID="+tableid+" for update");   
		    if (rs.next())   
		    {   
		        //得到java.sql.Blob对象后强制转换为oracle.sql.BLOB   
		        oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("FPMSLT");   
		        OutputStream outStream = blob.getBinaryOutputStream();
		        //data是传入的byte数组,定义:byte[] data   
		        outStream.write(data, 0, data.length);
			    outStream.flush();   
			    outStream.close(); 
		    }   
  
		    con.commit();   
		    con.close();   
	}

第四步:查看数据库

在这里插入图片描述

你可能感兴趣的:(Java向数据库orcale中类型为Blob字段赋值)