Pages Navigation Menu

Coding is much easier than you think

JDBC Statement Example to Update a Record

JDBC Statement Example to Update a Record

 
Here’s an example to show you how to update a record in a table via JDBC statement.
 
To issue an update statement, call the Statement.executeUpdate() method like this :
 

Statement statement = connection.createStatement();
// execute update SQL stetement
statement.executeUpdate(updateTableQurey);

 
Full example…
File: JDBCStatementUpdateExample.java
 

package com.simplecode.jdbc;

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

public class JDBCStatementUpdateExample  
{
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 
	{
		updateRecordIntoEmployeeTable();
	}
	
	catch (SQLException e) 
	{
		System.out.println(e.getMessage());
	}
}

private static void updateRecordIntoEmployeeTable() throws SQLException 
{
	Connection connection = null;
	Statement statement = null;

	String updateTableQurey = "UPDATE EMPLOYEE SET USERNAME = 'Azar' " 
								+ "WHERE USER_ID = 1000";
	try 
	{
		connection = getDBConnection();
		statement = connection.createStatement();

		// execute update SQL statement
		statement.executeUpdate(updateTableQurey);
		System.out.println("Record is updated to EMPLOYEE table!");

	}
	
	catch (SQLException e) 
	{
		System.out.println(e.getMessage());
	}
	
	finally 
	{

		if (statement != null) 
		{
			statement.close();
		}

		if (connection != null) 
		{
			connection.close();
		}
	}
}

	private static Connection getDBConnection() 
	{

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

		try 
		{
		dbConnection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
		return dbConnection;

		}
		catch (SQLException e) 
		{
			System.out.println(e.getMessage());
		}

		return dbConnection;
	}
}

 

dwd2
Download It – JDBCStatementUpdateExample

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.