如何将图片存到数据库(以mysql为例), 使用ORM Bee更加简单

如何将图片存到数据库

  1. 创建数据库:
  1. 生成Javabean
java 复制代码
public class ImageExam implements Serializable {

	private static final long serialVersionUID = 1596686274309L;

	private Integer id;
	private String name;
//	private Blob image;
	private InputStream image; //将InputStream存入blob
	private byte[] binary1; //存byte[]
	private byte[] binary2blob; //将byte[]存入blob

省略相应的get,set

  1. 使用ORM Bee对表时行插入数据和查询:
java 复制代码
package org.teasoft.exam.bee.osql;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import org.teasoft.bee.osql.api.Suid;
import org.teasoft.exam.bee.osql.entity.ImageExam;
import org.teasoft.exam.comm.Printer;
import org.teasoft.honey.osql.shortcut.BF;
import org.teasoft.honey.util.StreamUtil;

/**
 * @author Kingstar
 * @since  2.1.10
 */
public class ByteArrayOrBlobExam {

	public static void main(String[] args) throws Exception {
		Suid suid=BF.getSuid();

		ImageExam imageExam = new ImageExam();

		String filePath = "F://testPic.jpg";
		File imageFile = new File(filePath);
		FileInputStream inputStream = new FileInputStream(imageFile);

		imageExam.setImage(inputStream); //将InputStream存入blob
		
		String str = "Hello, World!";
		byte[] byteArray = str.getBytes();
		imageExam.setBinary1(byteArray);  //存byte[]
		imageExam.setBinary2blob(byteArray); //将byte[]存入blob
		suid.insert(imageExam);
		
		ImageExam imageSelect = new ImageExam();
		imageSelect.setId(473684481);
//		imageSelect.setBinary1(byteArray); //不能用于过滤
		
		List<ImageExam> list=suid.select(imageSelect);
		Printer.printList(list);
		StreamUtil.inputStream2File(list.get(0).getImage(), "F://testPic2.jpg");
		
		
		System.out.println(StreamUtil.byteArray2String(list.get(0).getBinary1()));
		System.out.println(StreamUtil.byteArray2String(list.get(0).getBinary2blob()));

	}

}

获取数据库的图片,并保存到指定位置:

StreamUtil.inputStream2File(list.get(0).getImage(), "F://testPic2.jpg");

此实例也演示了,如何设置inputStream, byte[]到数据库;

另外,inputStream是可以设置到mysql的blob字段的

相关推荐
凉栀お_4 小时前
MySQL第四次作业(索引、视图)
数据库·mysql
IT教程资源C5 小时前
(N_083)基于springboot毕业设计管理系统
mysql·springboot毕业管理
计算机小手6 小时前
探索 Maxwell:高效捕获 MySQL 数据变更的轻量级中间件
数据库·经验分享·mysql·开源软件
喝杯牛奶丶11 小时前
MySQL隔离级别:大厂为何偏爱RC?
java·数据库·mysql·面试
Dxy123931021613 小时前
MySQL的UPPER函数介绍
数据库·mysql
api_1800790546013 小时前
请求、认证与响应数据解析:1688 商品 API 接口深度探秘
java·大数据·开发语言·mysql·数据挖掘
yuezhilangniao14 小时前
mysql mogoDB pg redis-四大数据库选型-数据库对比大白话指南
数据库·redis·mysql
南宫乘风1 天前
基于 Flask + APScheduler + MySQL 的自动报表系统设计
python·mysql·flask
Dxy12393102161 天前
MySQL的SUBSTRING函数详解与应用
数据库·mysql
码力引擎1 天前
【零基础学MySQL】第十二章:DCL详解
数据库·mysql·1024程序员节