Share on Google+Share on Google+

Update Record using Prepared Statement

In this section, you will learn how to update row using Prepared Statements.

JDBC: Update Record using Prepared Statement

In this section, you will learn how to update row using Prepared Statements.

Update Record   : Prepared statement is good to use where you need to execute same SQL statement many times for different values. It is precompiled SQL Statements which are stored in a PreparedStatement object. Now you can use this object to execute this statement many times. It is the best way to reduce execution time and improve performance. So if you want to update many rows, you can use Prepared statement.
Update record is most important operation of database. You can update one field or many fields under certain condition.

executeUpdate(String sql): This method executes SQL statements(insert, update or delete)in PreparedStatement object, which takes the SQL query of string type and returns int.

Example : In this example we are updating student name as "Julu" whose roll_no is 3.

package jdbc;

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

class PreparedStmUpdate {
	public static void main(String[] args) {
		System.out.println("Update Record using PreparedStatement...");
		Connection con = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		PreparedStatement st = null;
		try {
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {

				// updating records
				String sql = "UPDATE student SET name=? WHERE roll_no=?";
				st = con.prepareStatement(sql);
				st.setString(1, "Julu");
				st.setInt(2, 3);
				System.out.println("Updated successfully");

			} catch (SQLException s) {
		} catch (Exception e) {


Output :

Update Record using PreparedStatement...
Updated successfully


Posted on: October 3, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null