把blob数据放到服务器的硬盘里

本文介绍如何从db2数据库中读取Blob数据,并将其存储到服务器的硬盘目录中,涉及时间戳处理和数据库连接建立。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、通过传递参数读取db2的blob数据放到服务器的硬盘目录

	/**
	 * 从三项查询出来文件数据放到服务器的webapps的jj目录
	 * @param path,路径
	 * @param dateStr,时间戳
	 * @param fileName,文件名称
	 * @param itemId,项目id
	 */
	public void findByAttachment(String path,String dateStr,String fileName,String itemId){
		String sql = "select fileInfo.file_obj from V_INSPECT_FILE_INFO AS fileInfo " +
				"where to_char(fileInfo.ITEM_ID) = '"+itemId+"'";
		  Connection con = HibernateSessionFactory.makeConnection();
		    try {
				con.setAutoCommit(false);
				Statement st = con.createStatement();
				ResultSet rs = st.executeQuery(sql);
				while (rs.next()) {
					java.sql.Blob blob = rs.getBlob(1);
					InputStream ins = blob.getBinaryStream();
					File pathFile = new File(path);
					if(!pathFile.exists()){
						pathFile.mkdirs();
					}
					//输出到文件
					File file = new File(path+dateStr+fileName);
					if(!file.exists()){   
		                file.createNewFile();   
		            } 
					OutputStream fout = new FileOutputStream(file);
					//下面将BLOB数据写入文件
					byte[] b = new byte[1024];
					int len = 0;
					while ( (len = ins.read(b)) != -1) {
						fout.write(b, 0, len);
					}
					//依次关闭
					fout.close();
					ins.close();
				}    
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					con.commit();
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
	}


二、时间戳

String dateStr = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());


 

三、创建与数据库的连接

	public static final String url = "jdbc:db2://10.20.0.185:50001/sx1";  
    public static final String username = "sxzmusr1";  
    public static final String password = "sxzmusr1";  
    public static final String driverClassName = "com.ibm.db2.jcc.DB2Driver";  
	public static Connection makeConnection() {  
        Connection conn = null;  
        try {  
            Class.forName(driverClassName);  
        } catch (ClassNotFoundException e) {  
            e.printStackTrace();  
        }  
        try {  
            conn = DriverManager.getConnection(url, username, password);  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
        return conn;  
    }  


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值