Pages Navigation Menu

Coding is much easier than you think

JDBC PreparedStatement example to Update a Record

JDBC PreparedStatement example to Update a Record

 
In this example let us learn how to update a record in table via JDBC PreparedStatement.
 
To issue a update statement, calls the PreparedStatement.executeUpdate() method as shown below :
 

String updateTableQuery = "UPDATE EMPLOYEE SET USERNAME = ? WHERE USER_ID = ?";
connection = getDBConnection();
prepareStmt = connection.prepareStatement(updateTableQuery);
prepareStmt.setString(1, "Nilafar Nisha");
prepareStmt.setInt(2, 1000);
 
// execute update SQL statement
prepareStmt.executeUpdate();

 
Full example.
 

package com.simplecode.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCPreparedStmtUpdateExample
{
private static final String dbDriver = "oracle.jdbc.driver.OracleDriver";
private static String serverName = "127.0.0.1";
private static String portNumber = "1521";
private static String sid = "XE";
private static final String dbUrl = "jdbc:oracle:thin:@" + serverName + ":"
		+ portNumber + ":" + sid;
private static final String dbUser = "system";
private static final String dbPassword = "admin";

public static void main(String[] argc)
{
	try
	{
		insertRecordIntoTable();
	}
	catch (SQLException e)
	{
		System.out.println(e.getMessage());
	}
}

private static void insertRecordIntoTable() throws SQLException
{
	Connection connection = null;
	PreparedStatement prepareStmt = null;
	String updateTableQuery = "UPDATE EMPLOYEE SET USERNAME = ? WHERE USER_ID = ?";

	try
	{
		connection = getDBConnection();
		prepareStmt = connection.prepareStatement(updateTableQuery);

		prepareStmt.setString(1, "Nilafar Nisha");
		prepareStmt.setInt(2, 1000);
		// execute update SQL statement
		prepareStmt.executeUpdate();
		System.out.println("Record is updated to EMPLOYEE table!");
	}
	catch (SQLException e)
	{
		System.err.println(e.getMessage());
	}
		
	finally
	{
		if (prepareStmt != null)
		{
			prepareStmt.close();
		}
		if (connection != null)
		{
			connection.close();
		}
		}
}

private static Connection getDBConnection()
{
	Connection dbConnection = null;
	try
	{
		Class.forName(dbDriver);
	}
	catch (ClassNotFoundException e)
	{
		System.err.println(e.getMessage());
	}

	try
	{
	dbConnection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
	return dbConnection;
	}
	catch (SQLException e)
	{
		System.err.println("Db "+e.getMessage());
	}
	return dbConnection;
}
}

 

About Mohaideen Jamil