JDBC处理大文本之BLOB

本文详细介绍如何将Blob类型数据写入数据库以及从数据库读取Blob数据并保存到本地的方法。包括使用PreparedStatement设置Blob值,以及从ResultSet中获取Blob数据。

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

接着上一讲的内容,直接看下面的代码。

       ①将blob类型的数据写入数据库中:

/**
	 * 将blob类型的数据写入数据库中
	 * @param student
	 * @return
	 * @throws Exception
	 */
	public static int  addStudent(Student student) throws Exception{
		Connection conn = dbUtils.getConnetction(); //获取数据库连接
		String sql = "insert into zhanghua values(null,?,?,?,?)";   //执行数据库sql的写法
		PreparedStatement psmt = conn.prepareStatement(sql); //获取prepareStatement对象
		psmt.setString(1, student.getUserName()); //设置第一个参数的值
		psmt.setInt(2, student.getAge()); //设置第二个参数的值
	    
	    //将clob类型字段写入数据库中
		File file = student.getContent();  //获取大文件
		InputStream inputStream = new FileInputStream(file);
		psmt.setAsciiStream(3, inputStream,file.length()); //设置第三个参数值
		
		//将blob类型字段写入数据库中
		File file_pic = student.getPic();  //获取图片
		InputStream inputStream_pic = new FileInputStream(file_pic);
		psmt.setBinaryStream(4, inputStream_pic, file_pic.length()); //设置第四个参数的值
		
		int result = psmt.executeUpdate();
		dbUtils.close(psmt, conn);
		
		return result;
	}

      ②从数据库中读取blob类型的字段,并存在本地:

/**
	 * 通过id查询学生
	 * @param id
	 * @throws Exception
	 */
	public static void findStudentById(int id) throws Exception{
		Connection conn = dbUtils.getConnetction(); //获取数据库连接
		String sql = "select * from zhanghua where id = ?";   //执行数据库sql
		PreparedStatement psmt = conn.prepareStatement(sql); //获取prepareStatement对象
		psmt.setInt(1, id);
		
		ResultSet rs = psmt.executeQuery();
		if(rs.next()){
			String username = rs.getString("username"); //学生姓名
			int age = rs.getInt("age"); //年龄
			
            //从数据库中读取clob类型的字段
			Clob clob = rs.getClob("content"); //获取大文本
			String content = clob.getSubString(1, (int)clob.length());

			//从数据库中读取blob类型的字段
			Blob blob = rs.getBlob("pic");
			OutputStream out = new FileOutputStream(new File("D:/22.JPG"));
			out.write(blob.getBytes(1,(int)blob.length()));
			
			System.out.println("学生姓名为: "+ username);
			System.out.println("学生年龄: "+ age);
			System.out.println("大文本: "+ content);
		}
		dbUtils.close(psmt, conn);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值