Views :- 349

How to update record using java jdbc

Here is an example to demonstate you how to update record using JDBC statement. To perform update we need use Statement.executeUpdate() method.

Refer the below example to update the record using JDBC.
Get the Statement from Jdbc Connection. Statement object use to sending SQL statements to the database.

Statement statement = connection.createStatement();

Executes the below SQL statement, Which is used to Manipulation the data. Here we are going to update the salary of employee id = 4.


int affectedrecords = statement.executeUpdate("UPDATE trn_employee SET emp_salary=25000 WHERE emp_id=4");


Above executeUpdate() method is used to Data Manipulation. It returns number of records which are updated, otherwise it return zero records if nothing is manipulated.

package com.net.example;

import java.sql.*;

public class JdbcMysqlUpdateExample {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JdbcMysqlUpdateExample jdbcMysqlSelectExample = new JdbcMysqlUpdateExample();
		Connection connection = jdbcMysqlSelectExample.getConnection();
		Statement statement = null;
		try {
			statement = connection.createStatement();
			// execute update query
			int affectedrecords = statement.executeUpdate("UPDATE trn_employee SET emp_salary=25000 WHERE emp_id=4");
			System.out.println("Records Updated.." + affectedrecords) ;

		} catch (SQLException e) {
			System.out.println("SQLException Occured..");
		} finally {
			try {
				if (statement != null) {
					statement.close(); // close statement
				}

				if (connection != null) {
					connection.close(); // close connection
				}
			} catch (SQLException e) {
				System.out.println("SQLException Occured..");
			}
		}

	}

	/***
	 * Get Connection
	 * 
	 * @return
	 */
	private Connection getConnection() {
		Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/technicalkeeda", "root", "");

		} catch (ClassNotFoundException e) {
			System.out.println("ClassNotFoundException Occured...");
		} catch (SQLException e) {
			System.out.println("SQLException Occured...");
		}

		return connection;
	}
}


Output

Number of Records Updated..1


java 

Current Donation 10 $

You also Like this Tutorials

HTML Comment Box is loading comments...

Other Posts

 
Hi I am Yashwant founder of www.technicalkeeda.com, Purpose of this website to share the programming knowledge in the form post , blogs and articles.
 

| Rss Feed | Contact Us | Find us on Google+