数据库Blob数据类型的操作

这篇博客介绍了MySQL中的Blob数据类型,用于存储大量二进制数据。内容包括四种不同类型的Blob,如何使用PreparedStatement插入Blob数据,以及如何查询并下载Blob数据到本地文件。示例代码展示了插入和查询Blob字段的过程。
摘要由CSDN通过智能技术生成

1.Blob数据类型

  • MySQL中,Blob是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
  • 插入BLOB类型的数据必须使用PreparedStatement,因为BLOB类型的数据无法使用字符串拼接写的。
  • MySQL的四种BLOB类型
  • 实际使用中根据需要存入的数据大小定义不同的BLOB类型

2.向数据表内插入Blob数据类型

          示例代码:代码执行后,图片可以在数据库内预览

	publicvoidinsert(){
		Connection conn=null;
		PreparedStatement ps=null;
		try{
			//获取连接
			conn=JDBCUtils.getConnection();
			String sql="insert into customers(name,email,birth,photo)values(?,?,?,?)";
			//预加载sql语句
			ps=conn.prepareStatement(sql);
			
			//填充占位符
			ps.setObject(1,"EVA");
			ps.setObject(2,"eva@123.com");
			ps.setObject(3,"2000-01-01");
			FileInputStream is=new FileInputStream(newFile("eva.jpg"));//图片需要io流进行传入
			ps.setBlob(4,is);//传入文件流
			//执行语句
			ps.execute();
		}catch(Exceptione){
			e.printStackTrace();
		}finally{
			//关闭连接
			JDBCUtils.closeResource(conn,ps);
		}
	
	}

3.查询数据表内的Blob数据

          查询Blob类型的数据,将其下载在项目路径下。

	publicvoidqueryBlob(){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		InputStream is=null;
		FileOutputStream fos=null;
		
		try{
		//1.获取连接
		conn=JDBCUtils.getConnection();
		
		//2.预加载sql语句
		Stringsql="select id,name,email,birth,photo from customers where id=?";
		ps=conn.prepareStatement(sql);
		ps.setInt(1,16);
		
		//3.执行语句,获取结果集
		rs=ps.executeQuery();
		
		//4.操作结果集
		if(rs.next()){
			//根据列名获取对应实例
			int id=rs.getInt("id");
			String name=rs.getString("name");
			String email=rs.getString("email");
			Date birth=rs.getDate("birth");
			
			//将非blob类型的数据存入对象输出在控制台
			Customer customer=new Customer(id,name,email,birth);
			System.out.println(customer);
			//Blob类型字段需要单独操作
			//获取Blob类型字段,并将其下载下来,以文件的当时保存
			Blob photo=rs.getBlob("photo");
			is=photo.getBinaryStream();//以流的方式进行保存
			fos=new FileOutputStream("朱茵.jpg");//设置输出的文件名
			byte[] buffer=new byte[1024];
			int len;
			while((len=is.read(buffer))!=-1){
				fos.write(buffer,0,len);
			}
		}
		}catch(Exceptione){
			e.printStackTrace();
		}finally{
			JDBCUtils.closeResource(conn,ps,rs);
		try{
			if(is!=null)
				is.close();
			}catch(IOExceptione){
				e.printStackTrace();
			}
		try{
			if(fos!=null)
				fos.close();
			}catch(IOExceptione){
				e.printStackTrace();
			}
		}
	}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值