JDBC batch update with Statement

By | July 18, 2018

When you want to send a bunch of SQL queries to database in one go(one call) to execute that’s what batch concept comes.
This reduces network traffic and improves performance of your application

In this post we will learn about JDBC batch update with java.sql.Statement.

As you know  java.sql.Statement always deals with Literal or hard coded SQL.
So here we have some hard coded SQL queries in ClientTest.java and all these SQL queries will execute in single database call using Jdbc batch. I mean to say we are not going to make separate database call for every SQL query.

Project structure in eclipse:

DB Script to create employee_table(database schema jdbcdb)

DBUtil.java class which is responsible to connect with MySQL database.
this util class uses getConnection() method of java.sql.DriverManager class
public static Connection getConnection(String url,String user, String password) throws SQLException
This method takes three parameters database URL,username and password.
Here database username =”root”,password  = “root”  what password had supplied during MYSQL database installation time and finally database URL =“jdbc:mysql://localhost:3306/jdbcdb” Where jdbc is the API, mysql is the database, localhost is the server name on which mysql  database server is running, we may also use IP address instead machine name, 3306 is the port number and jdbcdb(Make you you have created this schema in MySQL database) is the database name. You may use any database name, in that case, You need to replace the jdbcdb with your database name.

Client program 
In this client program we have three SQL queries which we have added in jdbc statement object by calling addBatch(String sqlQuery) method and finally when we call executeBatch() method all these SQL queries send to database in one go.

After running client program you will get below output on IDE console:

Here value :1 says query executed successfully and value:0 says there is no employee with id:20

That’s all for this topic JDBC batch update with Statement.

Leave a Reply

Your email address will not be published. Required fields are marked *