如何将图片存到数据库(以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字段的

相关推荐
叁沐20 分钟前
MySQL 02 日志系统:一条SQL更新语句是如何执行的?
mysql
RunsenLIu28 分钟前
基于Vue.js + Node.js + MySQL实现的图书销售管理系统
vue.js·mysql·node.js
码不停蹄的玄黓38 分钟前
MySQL Undo Log 深度解析:事务回滚与MVCC的核心功臣
数据库·mysql·undo log·回滚日志
Arthurmoo1 小时前
Linux系统之MySQL数据库基础
linux·数据库·mysql
Tangcan-1 小时前
【MySQL】 内置函数
mysql
找不到、了2 小时前
MySQL的窗口函数介绍
数据库·mysql
执笔诉情殇〆3 小时前
springboot集成达梦数据库,取消MySQL数据库,解决问题和冲突
数据库·spring boot·mysql·达梦
软件技术NINI3 小时前
springMvc的简单使用:要求在浏览器发起请求,由springMVC接受请求并响应,将个人简历信息展示到浏览器
数据库·mysql
九分源码7 小时前
基于PHP+MySQL组合开发开源问答网站平台源码系统 源码开源可二次开发 含完整的搭建指南
mysql·开源·php
程序员岳焱7 小时前
Java 与 MySQL 性能优化:MySQL分区表设计与性能优化全解析
后端·mysql·性能优化