JDBC batch update with PreparedStatement

By | July 18, 2018

When you want to send a bunch of SQL queries to database in one database 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.PreparedStatement.
As you know  java.sql.PreparedStatement deals with dynamic SQL with place holder(?).
so Here we have one dyamic SQL query with two place holder(?) and these parameter values we will set dynamically
“UPDATE employee_table set salary=? WHERE employee_id=?”

Have look in ClientTest.java class how we have used above 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 an dynamic SQL update query  with place holder(?) .Here basically we are going to update salary of more  than one employees based on his/her employee id.

Every time after setting employee new salary and id. which we have added in PreparedStatement object(ps) by calling addBatch() method and finally when we call executeBatch() method all these updates will send to database in one go.

After running client program you will give below output on IDE console:
1
0
0

employee_table in database schema(jdbcdb)

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

Leave a Reply

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