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

相关推荐
zhou周大哥13 小时前
银河麒麟安装mysql
数据库·mysql
Sherry Wangs14 小时前
MySQL 与向量数据库的核心区别:从结构化数据到语义搜索
数据库·mysql
@小柯555m14 小时前
MySql(高级操作符--高级操作符练习(2))
数据库·sql·mysql
zxrhhm14 小时前
MySQL Server层与InnoDB存储引擎的关系+两阶段提交详解
mysql
Mr_linjw14 小时前
MySQL 中监控和优化慢 SQL & 索引小知识
数据库·sql·mysql
计算机学姐14 小时前
基于微信小程序的校园失物招领管理系统【uniapp+springboot+vue】
java·vue.js·spring boot·mysql·信息可视化·微信小程序·uni-app
落魄江湖行14 小时前
孤舟笔记 并发篇十一 行锁、间隙锁、临键锁傻傻分不清?MySQL InnoDB的锁其实就这三板斧
mysql·java并发·春招·孤舟笔记
zhoupenghui16814 小时前
Mysql插入数据时,怎么让自增的主键续接表当前最大ID+1
数据库·mysql·auto increment
song85460113415 小时前
MYSQL优化器的主要的优化策略及其示例
数据库·mysql
Bert.Cai15 小时前
MySQL RAND()函数详解
数据库·mysql