JDBC-day03(BLOB类型字段,批量插入)

news/2025/2/1 9:53:55/

四:操作BLOB类型字段

1.MySQL BLOB类型

  • 在MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。可以用来存储图片,视频等

  • 插入BLOB类型的数据必须使用PreparedStatement,因为BLOB类型的数据无法使用字符串拼接写的。

  • MySQL的四种BLOB类型(除了在存储的最大信息量上不同外,他们是等同的)
    在这里插入图片描述

  • 实际使用中根据需要存入的数据大小定义不同的BLOB类型。

  • 如果在指定了相关的Blob类型以后,还报错:xxx too large,那么在mysql的安装目录下,找my.ini文件加上如下的配置参数: max_allowed_packet=16M。同时注意:修改了my.ini文件之后,需要重新启动mysql服务。

2.向数据表customer中插入Blob类型的字段

public class BlobTest {@Testpublic void testInsert() throws Exception {Connection conn = null;                          PreparedStatement ps = null;try {conn = JDBC_Utils.getConnection();String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";ps = conn.prepareStatement(sql);ps.setObject(1, "张杰");ps.setObject(2, "ZhangJie@168.com");ps.setObject(3, "1992-09-08");FileInputStream is = new FileInputStream(new File("zhangjie.jpg"));//如果文件大于1MB,可能会报xxx too large错误,解决方法参照上面的解决方式ps.setBlob(4, is);ps.execute();} catch (Exception e) {e.printStackTrace();}finally {JDBC_Utils.closeResource(conn, ps);}}
}

注:在工作目录下要有zhangjie.jpg,否则会提示找不到文件

3.查询数据表customer中的Blob字段

	@Testpublic void testQuery(){Connection conn = null;      PreparedStatement ps = null;ResultSet rs = null; InputStream is = null;FileOutputStream fos = null;try { conn = JDBC_Utils.getConnection();String sql = "select id,name,email,birth,photo from customers where id = ?"; ps = conn.prepareStatement(sql);ps.setInt(1,21);rs = ps.executeQuery(); if(rs.next()) { //使用列的别名来查找int id = rs.getInt("id");String name = rs.getString("name");String email = rs.getString("email"); Date birth = rs.getDate("birth");Customer customer = new Customer(id,name,email,birth);System.out.println(customer); //将Blob类型的字段下载下来,以文件的形式保留到本地Blob photo = rs.getBlob("photo");is = photo.getBinaryStream();fos = new FileOutputStream("singer.jpg");byte[] buffer = new byte[1024];int len;while((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len);}}} catch (Exception e) {e.printStackTrace();}finally {try { if(is != null) is.close(); } catch (IOException e) {e.printStackTrace();}try { if(fos != null) fos.close();} catch (IOException e) {e.printStackTrace();}JDBC_Utils.closeResource(conn, ps, rs); }}

五:批量插入

1.批量操作

当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率

JDBC的批量处理语句包括下面三个方法:

  • addBatch(String):添加需要批量处理的SQL语句或是参数;
  • executeBatch():执行批量处理语句;
  • clearBatch():清空缓存的数据

通常我们会遇到两种批量执行SQL语句的情况:

  • 多条SQL语句的批量处理;
  • 一个SQL语句的批量传参;

2.高效的批量插入

  • 使用PreparedStatement实现批量数据操作
  • update,delete本身就具有批量操作的效果
  • 此时的批量操作,主要指批量插入

例: 题目向goods表添加100万条数据

 CREATE TABLE goods(id INT PRIMARY KEY AUTO_INCREMENT,       NAME VARCHAR(25)
);
import java.sql.Connection;                                      
import java.sql.PreparedStatement;import org.junit.Test;import com.jdbc.util.JDBC_Utils;public class InsertTest {//方式一:使用Statement批量插入数据(略)//方式二:使用PreparedStatement批量插入数据@Testpublic void testInsert1() {Connection conn = null;PreparedStatement ps = null;try {long start = System.currentTimeMillis();conn = JDBC_Utils.getConnection();String sql = "insert into goods(name)values(?)";ps = conn.prepareStatement(sql);for(int i = 1;i <= 1000000;i++) {ps.setObject(1,"name_" + i);ps.execute();}long end = System.currentTimeMillis();System.out.println("插入花费时间为:" + (end - start) + "毫秒");//1350941毫秒---8473毫秒---5857毫秒} catch (Exception e) {e.printStackTrace();}finally {JDBC_Utils.closeResource(conn, ps);}	}
}

方式三:使用addBatch(),executeBatch(),clearBatch()批量插入数据

  • mysql服务器默认关闭批处理,需要通过在url后添加?rewriteBatchedStatements=true来进行开启,不是mysqld的配置文件,是数据库连接的配置文件,即jdbc.properties

  • mysql驱动需要5.1.37及以上版本

    @Test
    public void testInsert2() {Connection conn = null;                                                        PreparedStatement ps = null;try { long start = System.currentTimeMillis();conn = JDBC_Utils.getConnection();String sql = "insert into goods(name)values(?)"; ps = conn.prepareStatement(sql);for(int i = 1;i <= 1000000;i++) {ps.setObject(1,"name_" + i);//1."攒"SQLps.addBatch();if(i % 500 == 0) {//2.执行batchps.executeBatch();//3.清空batchps.clearBatch(); }}long end = System.currentTimeMillis();System.out.println("插入花费时间为:" + (end - start) + "毫秒");} catch (Exception e) {e.printStackTrace();}finally {JDBC_Utils.closeResource(conn, ps);}
    }

方式四:设置连接不允许自动提交数据

	@Testpublic void testInsert3() {Connection conn = null;          PreparedStatement ps = null;try {long start = System.currentTimeMillis();conn = JDBC_Utils.getConnection();//设置不允许自动提交,默认执行SQL,就自动提交到数据库conn.setAutoCommit(false);String sql = "insert into goods(name)values(?)";ps = conn.prepareStatement(sql);for(int i = 1;i <= 1000000;i++) {ps.setObject(1,"name_" + i);//1."攒"SQLps.addBatch();if(i % 500 == 0) {//2.执行batchps.executeBatch();//3.清空batchps.clearBatch();}}//提交数据conn.commit();long end = System.currentTimeMillis();System.out.println("插入花费时间为:" + (end - start) + "毫秒");} catch (Exception e) {e.printStackTrace();}finally {JDBC_Utils.closeResource(conn, ps);}}

其中可能会出现不少的小问题,请多多包含
感谢大家的支持,关注,评论,点赞!
参考资料:尚硅谷_宋红康_JDBC核心技术


http://www.ppmy.cn/news/1140435.html

相关文章

Mybatis 使用参数时$与#的区别

之前我们介绍了mybatis中参数的使用&#xff0c;本篇我们在此基础上介绍Mybatis中使用参数时$与#的区别。 如果您对mybatis中参数的使用不太了解&#xff0c;建议您先进行了解后再阅读本篇&#xff0c;可以参考&#xff1a; Mybatis参数(parameterType)https://blog.csdn.net…

计算机系统基础第五、六周

复习 Lui指令 Lui a5,0x200>Lui a5,0x00200&#xff0c;补成20位 Lui a5,0x200表示将0x200这个值加载到a5寄存器的高20位中。但0x200只是一个12位的数值。为了将其展开为20位的形式&#xff0c;我们需要在它的前面补足相应数量的零。 所以&#xff0c;并不是200左移三位之…

基于vue框架的uniapp小程序开发发现了新大陆

项目场景&#xff1a; 在基于vue框架的uniapp小程序开发中&#xff0c;在页面跳转时&#xff0c;当前页路径带参数&#xff0c;在跳转页中接受数据除了用官方推荐的保留当前页面&#xff0c;跳转到应用内的某个页面&#xff0c;使用onLoad(option)接受数据&#xff0c;但是我发…

想要开发一款游戏, 需要注意什么?

开发一款游戏是一个复杂而令人兴奋的过程。游戏开发是指创建、设计、制作和发布电子游戏的过程。它涵盖了从最初的概念和创意阶段到最终的游戏发布和维护阶段的各个方面。 以下是一些需要注意的关键事项&#xff1a; 游戏概念和目标&#xff1a; 确定游戏开发的核心概念和目标…

【科学文献计量】pybibx模块安装与使用

pybibx模块安装与使用 1. pybibx模块介绍2. pybibx模块安装3. pybibx模块使用测试手动反爬虫: 原博地址 https://blog.csdn.net/lys_828/article/details/133674169 知识梳理不易,请尊重劳动成果,文章仅发布在CSDN网站上,在其他网站看到该博文均属于未经作者授权的恶意爬取…

基于SVM+TensorFlow+Django的酒店评论打分智能推荐系统——机器学习算法应用(含python工程源码)+数据集+模型(一)

目录 前言总体设计系统整体结构图系统流程图 运行环境Python环境TensorFlow 环境方法一方法二 安装其他模块安装MySQL 数据库 模块实现1. 数据预处理1&#xff09;数据整合2&#xff09;文本清洗3&#xff09;文本分词 相关其它博客工程源代码下载其它资料下载 前言 本项目以支…

SpringBoot项目:Cannot find declaration to go to

SpringBoot项目get,set方法总报Cannot find declaration to go to 搜了很多答案&#xff0c;没解决 后来仔细一想&#xff0c;原来是我的idea软件重装了&#xff0c;lombok插件没重新安装导致。 安装步骤&#xff1a; 1、下载地址&#xff1a;https://plugins.jetbrains.com…

2023-10-08 mysql-代号m-增加外键导致crash-问题分析

摘要: 2023-10-08 mysql-代号m-增加外键导致crash-问题分析 相关bug: https://devops.aliyun.com/projex/project/36ed2d8a9a29e7f8407c6f5498/bug/5e13f3c4165c590665a1693edf DDL: create table t1(c1 int primary key);create table t2(c2 int); alter table t2 add forei…