`
DavyJones2010
  • 浏览: 154266 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JDBC: Introduction to JDBC (Part III)-Batch Process

    博客分类:
  • JDBC
阅读更多

1.Batching with Statement Object

1) Batching with Create

package edu.xmu.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import edu.xmu.jdbc.bean.Student;

public class StudentDao {
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "****";
    private String password = "****";

    static {
	try {
	    Class.forName("com.mysql.jdbc.Driver");

	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	}
    }


    public void batchCreateStudent(List<Student> studentList) {
	Connection conn = null;
	Statement statement = null;

	try {
	    conn = DriverManager.getConnection(url, username, password);
	    statement = conn.createStatement();
	    conn.setAutoCommit(false);
	    for (Student student : studentList) {
		String sql = "insert into student(name, gender, age) values ('"
			+ student.getName() + "', '" + student.getGender()
			+ "', " + student.getAge() + ")";

		statement.addBatch(sql);
	    }
	    int[] count = statement.executeBatch();
	    conn.commit();
	    for (int i = 0; i < count.length; i++) {
		System.out.println(count[i]);
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	} finally {
	    try {
		statement.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    } finally {
		try {
		    conn.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	}
    }

}

2) Batching with Retrieve 

package edu.xmu.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import edu.xmu.jdbc.bean.Student;

public class StudentDao {
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "****";
    private String password = "****";

    static {
	try {
	    Class.forName("com.mysql.jdbc.Driver");

	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	}
    }

    // There is no a mechanism for select batches.
    public List<Student> batchRetrieveStudent(List<String> studentNameList) {
	Connection conn = null;
	Statement statement = null;
	List<Student> studentList = new ArrayList<Student>();
	try {
	    conn = DriverManager.getConnection(url, username, password);
	    statement = conn.createStatement();
	    conn.setAutoCommit(false);
	    String sql = "select name, gender, age from student where name in (";
	    for (String studentName : studentNameList) {
		sql += "'" + studentName + "', ";
	    }
	    sql = sql.substring(0, sql.length() - 2);
	    sql += ")";
	    System.out.println("Executing sql [" + sql + "]");
	    ResultSet resultSet = statement.executeQuery(sql.toString());

	    while (resultSet.next()) {
		String name = resultSet.getString("name");
		String gender = resultSet.getString("gender");
		int age = resultSet.getInt("age");
		Student student = new Student(name, gender, age);
		studentList.add(student);
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	} finally {
	    try {
		statement.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    } finally {
		try {
		    conn.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	}

	return studentList;
    }

}

Comments: As the statements in the link below, there in no mechanism for batch query. Probably because there is no apparant need for that.

                   As others have recommanded, you can simply retrieve all the rows you want at once by constructing the sql listed above.

3) Batching with Update

package edu.xmu.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import edu.xmu.jdbc.bean.Student;

public class StudentDao {
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "****";
    private String password = "****";

    static {
	try {
	    Class.forName("com.mysql.jdbc.Driver");

	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	}
    }

    public void batchUpdateStudent(List<Student> studentList) {
	Connection conn = null;
	Statement statement = null;

	try {
	    conn = DriverManager.getConnection(url, username, password);
	    statement = conn.createStatement();
	    conn.setAutoCommit(false);
	    for (Student student : studentList) {
		String sql = "update student set gender='"
			+ student.getGender() + "', age=" + student.getAge()
			+ " where name='" + student.getName() + "'";

		statement.addBatch(sql);
	    }
	    int[] count = statement.executeBatch();
	    conn.commit();
	    for (int i = 0; i < count.length; i++) {
		System.out.println(count[i] + " rows affected.");
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	} finally {
	    try {
		statement.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    } finally {
		try {
		    conn.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	}
    }
}

4) Batching with Delete

package edu.xmu.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class StudentDao {
    private String url = "jdbc:mysql://localhost:3306/jdbctest";
    private String username = "****";
    private String password = "****";

    static {
	try {
	    Class.forName("com.mysql.jdbc.Driver");

	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	}
    }

    public void batchDeleteStudent(List<String> studentNameList) {
	Connection conn = null;
	Statement statement = null;
	try {
	    conn = DriverManager.getConnection(url, username, password);
	    statement = conn.createStatement();
	    conn.setAutoCommit(false);
	    for (String studentName : studentNameList) {
		String sql = "delete from student where name='" + studentName
			+ "'";
		statement.addBatch(sql);
	    }
	    int[] count = statement.executeBatch();
	    conn.commit();

	    for (int i = 0; i < count.length; i++) {
		System.out.println(count[i] + " rows affected.");
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	} finally {
	    try {
		statement.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    } finally {
		try {
		    conn.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	}
    }
}

 

2. Batching with PreparedStatement Object

1) Batching with Create

    public void batchCreateStudent(List<Student> studentList) {
	Connection conn = null;
	PreparedStatement statement = null;
	String sql = "insert into student(name, gender, age) values(?, ?, ?)";
	try {
	    conn = DriverManager.getConnection(url, username, password);
	    statement = conn.prepareStatement(sql);
	    conn.setAutoCommit(false);
	    for (Student student : studentList) {
		statement.setString(1, student.getName());
		statement.setString(2, student.getGender());
		statement.setInt(3, student.getAge());
		statement.addBatch();
	    }
	    int[] count = statement.executeBatch();
	    conn.commit();
	    for (int i = 0; i < count.length; i++) {
		System.out.println(count[i] + " rows affected.");
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	} finally {
	    try {
		statement.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    } finally {
		try {
		    conn.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	}
    }

Comments: Attention that we should use "statement.addBatch();" instead of "statement.addBatch(sql);"

2) Batching with Retrieve

    // There is no a mechanism for select batches.
    public List<Student> batchRetrieveStudent(List<String> studentNameList) {
	Connection conn = null;
	PreparedStatement statement = null;
	List<Student> studentList = new ArrayList<Student>();
	try {
	    conn = DriverManager.getConnection(url, username, password);
	    String sql = "select name, gender, age from student where name in (";
	    for (int i = 0; i < studentNameList.size(); i++) {
		sql += "?, ";
	    }
	    sql = sql.substring(0, sql.length() - 2);
	    sql += ")";
	    statement = conn.prepareStatement(sql);
	    conn.setAutoCommit(false);
	    for (int i = 0; i < studentNameList.size(); i++) {
		String studentName = studentNameList.get(i);
		statement.setString(i + 1, studentName);
	    }
	    ResultSet resultSet = statement.executeQuery();

	    while (resultSet.next()) {
		String name = resultSet.getString("name");
		String gender = resultSet.getString("gender");
		int age = resultSet.getInt("age");
		Student student = new Student(name, gender, age);
		studentList.add(student);
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	} finally {
	    try {
		statement.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    } finally {
		try {
		    conn.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	}

	return studentList;
    }

Comments: Also, attention that we don't have and even don't need the batch select mechanism.

3) Batching with Update

    public List<Student> batchUpdateStudent(List<Student> studentList) {
	Connection conn = null;
	PreparedStatement statement = null;
	try {
	    conn = DriverManager.getConnection(url, username, password);
	    String sql = "update student set gender=?, age=? where name=?";
	    statement = conn.prepareStatement(sql);
	    conn.setAutoCommit(false);
	    for (Student student : studentList) {
		statement.setString(1, student.getGender());
		statement.setInt(2, student.getAge());
		statement.setString(3, student.getName());
		statement.addBatch();
	    }
	    int[] count = statement.executeBatch();
	    conn.commit();

	    for (int i = 0; i < count.length; i++) {
		System.out.println(count[i] + " rows affected.");
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	} finally {
	    try {
		statement.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    } finally {
		try {
		    conn.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	}

	return studentList;
    }

4) Batching with Delete

    public void batchDeleteStudent(List<String> studentNameList) {
	Connection conn = null;
	PreparedStatement statement = null;
	try {
	    conn = DriverManager.getConnection(url, username, password);
	    String sql = "delete from student where name=?";
	    statement = conn.prepareStatement(sql);
	    conn.setAutoCommit(false);
	    for (String studentName : studentNameList) {
		statement.setString(1, studentName);
		statement.addBatch();
	    }
	    int[] count = statement.executeBatch();
	    conn.commit();

	    for (int i = 0; i < count.length; i++) {
		System.out.println(count[i] + " rows affected.");
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	} finally {
	    try {
		statement.close();
	    } catch (SQLException e) {
		e.printStackTrace();
	    } finally {
		try {
		    conn.close();
		} catch (SQLException e) {
		    e.printStackTrace();
		}
	    }
	}
    }

Comments:

1) As we can see, there is a lot of redundancy code of creating statements and handling exceptions.

    Also, we may forget to close resultset, statements and connection.

    Therefore, we need a more efficient framework to avoid these defacts. Here come Sping-JDBC-Framework.

2) Also, we've seen that every time we execute a sql, we just created a new connection which is time consuming.

    Connection-Pool mechanism offers a better way of managing the connection resources.

 

Reference Links:

1. http://stackoverflow.com/questions/9853197/jdbc-batch-query-for-high-performance offers justification why we do not need batch select

2. http://www.tutorialspoint.com/jdbc/statement-batching-example.htm    offers detailed tutorials & example for batch CRD

3. http://www.javaranch.com/journal/200510/Journal200510.jsp#a2 offers several alternative options for batch select.

分享到:
评论

相关推荐

    JDBC:MySQL8.0.29驱动

    JDBC(Java Database Connectivity)是Java编程语言中用于与关系数据库交互的一种标准接口。它是Java平台的标准部分,允许开发人员使用SQL语言在Java应用程序中执行数据库操作。MySQL JDBC驱动,也称为MySQL ...

    README.mdgfdgdf

    |:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:|:-------:| | 25 | 28.57 | 28.83 | 28.68 | 28.96 | 28.74 | 28.92 | **29.23** | **29.16** | **29.17** | - Set...

    spring-batch同步数据库mysql源码

    针对MySQL数据库,Spring-Batch提供了一套完整的JDBC支持,允许开发者配置SQL查询来读取和更新数据。在描述中提到,项目已经移除了两个特定数据库的驱动库,这意味着默认配置是针对MySQL的。如果你需要支持Oracle或...

    IEC 61512-2:2001 批量控制--第二部分:数据结构和语言的准则 - 完整英文版(208页)

    完整英文版 IEC 61512-2:2001 Batch control - Part 2:Data structures and guidelines for languages(批量控制--第二部分:数据结构和语言的准则)。本标准关于批处理控制的这一部分定义了描述应用于过程工业的...

    memcached 1.2.6 1.2.5

    Call the cross-build.cmd batch file suppling the version of Visual Studio as the first parameter. See the contents of the cross-build.cmd file for all possibilities. This will build the Visual ...

    ANSI/ISA 88 Series(全系列)- Batch Control(批量控制) -包含7份最新英文版标准文件 .rar

    5,ANSI-ISA-88.00.04-2006 Batch Production Records - 完整英文电子版(86页).pdf 6,ISA TR88.95.01-2008 Using ISA-88 and ISA-95 Together - 完整英文版(57页).pdf 7,ISA-TR88.0,03-1996 Possible Recipe ...

    spring-batch-3.0.5.RELEASE-dist.zip

    在"spring-batch-3.0.5.RELEASE-dist.zip"这个压缩包里,包含了Spring Batch框架的核心组件和相关文档,允许开发者快速地集成和配置批处理作业。以下是一些关键的知识点: 1. **核心概念**: - **Job**:Spring ...

    Python库 | nf-batch-runner-0.0.11.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:nf-batch-runner-0.0.11.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    big-discriminator-batch-spoofing-gan:具有更多功能的BMSG-GAN

    "big-discriminator-batch-spoofing-gan:具有更多功能的BMSG-GAN" 这个标题提到了一个名为BMSG-GAN(可能代表Big Batch Spoofing Generator-Adversarial Network)的深度学习模型,它具有一个大的鉴别器和batch ...

    Python库 | tencentcloud-sdk-python-batch-3.0.381.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:tencentcloud-sdk-python-batch-3.0.381.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    Python库 | tencentcloud-sdk-python-batch-3.0.564.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:tencentcloud-sdk-python-batch-3.0.564.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    神经网络里的mini-batch算法.zip

    神经网络里的mini-batch算法神经网络里的mini-batch算法神经网络里的mini-batch算法神经网络里的mini-batch算法神经网络里的mini-batch算法神经网络里的mini-batch算法神经网络里的mini-batch算法神经网络里的mini-...

    gs-batch-processing-master2

    《gs-batch-processing-master2:批量处理指南与快速入门》 在IT行业中,批量处理(Batch Processing)是一种常见的数据处理方式,特别是在大数据分析、系统维护和自动化任务执行等领域。"gs-batch-processing-...

    mysql-connector-java-5.1.7-5.1.3-5.1.17

    MySQL Connector/J是MySQL数据库系统与Java应用程序之间的重要桥梁,它是一个实现了JDBC(Java Database Connectivity)规范的驱动程序,使得Java开发者能够方便地在Java应用中连接和操作MySQL数据库。"mysql-...

    gs-batch-processing3.0.7

    《Spring Batch 示例——深入理解gs-batch-processing3.0.7》 在IT行业中,Spring Batch作为Spring框架的一部分,已经成为批量处理和批处理任务的首选工具。本文将深入探讨"gs-batch-processing3.0.7"这个项目,它...

    EurekaLog_7.5.0.0_Enterprise

    11)..Fixed: Possible failure to handle/process stack overflow exceptions 12)..Changed: VCL/CLX/FMX now will assign Application.OnException handler when low-level hooks are disabled EurekaLog 7.2 ...

    yolov5目标检测模型的知识蒸馏(基于响应的蒸馏)

    --batch-size 8 --device 0 --hyp data/hyp.scratch.yaml 蒸馏训练: python train.py --weights weights/yolov5s.pt \ --cfg models/yolov5s.yaml --data data/voc.yaml --epochs 50 \ --batch-size 8 --device...

    计算机组成与结构体系英文课件:Chapter 8 – The Memory System - 2

    Algorithms such as Least Recently Used (LRU), First-In-First-Out (FIFO), and Random Replacement are employed to optimize this process. 3. Write Policy: This governs how data modifications are ...

    jdbc8.jar-oracle12

    Oracle JDBC驱动提供了许多性能优化选项,如批处理(batch processing)、预编译的语句(prepared statements)和连接池(connection pooling)。通过合理利用这些特性,可以显著提升应用的性能和可伸缩性。 总之,...

    Laravel开发-laravel-queue-aws-batch

    2. **安装扩展**:如果`laravel-queue-aws-batch-master`是一个GitHub仓库,你可以通过Composer来安装。在终端中运行: ``` composer require &lt;仓库名&gt; ``` 3. **配置Laravel**:在`config/queue.php`中添加AWS ...

Global site tag (gtag.js) - Google Analytics