Updating Data in Java

by | Dec 20, 2020 | Java

Home » Java » Updating Data in Java


After a database/table has been created and certain records have been inserted, to make changes to it, Java allows users to update records. In this article, we will discuss the process of updating records by making a new database and performing the necessary functions.

Steps to Create a new DB using JDBC application

  • The first step is to import the required packages. In this case, the java.sql.* has to be imported such that the JDBC classes can be used.
  • Next comes the registering of driver(s) to establish connections with the database.
  • Start the connection using the DriverManager.getConnection method.
  • To execute a query, you will first have to create an object of type Statement. This object will then perform the query request.
  • Once the query has been resolved, it is important to clean the environment by closing all the JDBC resources that were in use.


import java.sql.*;
public class JDBCExample
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main (String[] args)
Connection conn = null;
Statement stmt = null; try
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Registration " + "SET age = 20 WHERE id in (100, 101)"; stmt.executeUpdate(sql);
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
int id  = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}catch(SQLException se)
catch(Exception e)
if(stmt!=null) conn.close();
}catch(SQLException se)
{ }
if(conn!=null) conn.close();
}catch(SQLException se)



Connecting to a selected database…
Connected database successfully…
Creating statement…
ID: 100, Age: 20, First: Ahmed, Last: Shamim
ID: 101, Age: 20, First: Maesha, Last: Khan
ID: 102, Age: 20, First: Varun, Last:Agarwal
ID: 103, Age: 40, First: Rohan, Last: Roy


Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.