Updating Data in Java

Introduction

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.

Example

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
{
Class.forName("com.mysql.jdbc.Driver");
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);
while(rs.next())
{
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);
}
rs.close();
}catch(SQLException se)
{
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
try
{
if(stmt!=null) conn.close();
}catch(SQLException se)
{ }
try
{
if(conn!=null) conn.close();
}catch(SQLException se)
{
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}

 

OUTPUT

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
Goodbye!

Leave a comment

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