JDBC方式将数据库中Blob类型转成base64图片

 sql2 = "select zp from T_EXAM_PROCESS  where id='"+id+"'  and anytime like '"+anytime+"%'";
                listZp2 = oracleUtil.searchSql2(sql2,newdburl,newdbname,newdbpassword,keyList2);

 

//参数配置类
@Autowired
private PropConfig Config;

sql2 = "select zp from T_EXAM_PROCESS  where id='"+id+"'  and anytime like '"+anytime+"%'";
listZp2 = oracleUtil.searchSql2(sql2,newdburl,newdbname,newdbpassword,keyList2);
/*
	 * 执行sql,获得单字段,放在集合返回
	 */
	public static List searchSql2(String sql,String k2dburl,String k2dbusername,String k2dbpassword,List list){
			List jay=new ArrayList();
		    Connection con = null;// 创建一个数据库连接
		    PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
		    ResultSet result = null;// 创建一个结果集对象
		    try{
		        Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
		        System.out.println("开始尝试连接数据库!");
		        String url = "jdbc:oracle:" + k2dburl;// 127.0.0.1是本机地址,XE是精简版Oracle的默认数据库名
		        String user = k2dbusername;// 用户名,系统默认的账户名
		        String password = k2dbpassword;// 你安装时选设置的密码
		        con = DriverManager.getConnection(url, user, password);// 获取连接
		        System.out.println("连接成功!");
		        pre = con.prepareStatement(sql);// 实例化预编译语句
		        result = pre.executeQuery();// 执行查询,注意括号中不需要再加参数
		        while (result.next()) {
		        	for (String key:list) {
		        		if (key.equals("zp")) {
		        			String name = UUID.randomUUID().toString();
		        			Blob zp = result.getBlob("zp");
		        			if (zp==null || zp.equals("")) {
								continue;
							}
		        			String filepath = "D:/tempZp/" +name + ".jpg";
		    				InputStream input = zp.getBinaryStream();
		    				FileOutputStream out = new FileOutputStream(filepath);
		    				int len = (int) zp.length();
		    				//添加项目时,如果没有添加照片,此时len=0,则跳过即可;
		    				if (len==0) {
								continue;
							}
		    				byte buffer[] = new byte[len];
		    				while ((len = input.read(buffer)) != -1) {
		    					out.write(buffer, 0, len);
		    				}
		    				out.close();
		    				input.close();
		    				String image64 = ImageBase64.getImageStr(filepath);
		    				jay.add(image64);
		    				File file  = new File(filepath);
		    				file.delete();
						}else if(key instanceof String){
							jay.add(result.getString(key));
						}
					}
				} 
		    }catch (Exception e){
		        e.printStackTrace();
		    }finally{
		        try{
		            // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
		            // 注意关闭的顺序,最后使用的最先关闭
		            if (result != null)
		                result.close();
		            if (pre != null)
		                pre.close();
		            if (con != null)
		                con.close();
		            System.out.println("数据库连接已关闭!");
		        }catch (Exception e)
		        {
		            e.printStackTrace();
		        }
		    }
		    return jay;
	}

 

你可能感兴趣的:(JDBC方式将数据库中Blob类型转成base64图片)