PreparedStatement is an interface and has pre-compiled SQL statements. PreparedStatements are used to efficiently execute the same SQL statement multiple times. They are also used to set the parameters in query dynamically.
Steps to Update record using Prepared Statement
1. Get a connection Object
1 |
Connection connection = getConnection(); |
2. Create a prepareStatement object
1 2 3 |
String updateSql = "UPDATE employee_details" + " SET designation= ? WHERE salary = ?"; PreparedStatement preparedStatement = connection.prepareStatement(updateSql); |
3. Add parameters (if required)
1 2 |
preparedStatement.setString(1, "Sr Developer"); preparedStatement.setInt(2, 1000); |
ParameterIndex starts from 1.
4. execute the query using executeUpdate.
1 |
int rowCount = preparedStatement.executeUpdate(); |
Full Example : Update record using Prepared Statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package com.kscodes.sampleproject.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class PreparedUpdateExample { public static String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; public static String CONNECTION_URL = "jdbc:mysql://localhost:3306/mysql"; public static String CONNECTION_USER = "kscodes"; public static String CONNECTION_PASSWORD = "kscodes"; public static void main(String[] args) { String updateSql = "UPDATE employee_details" + " SET designation= ? WHERE salary = ?"; try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection .prepareStatement(updateSql)) { preparedStatement.setString(1, "Sr Developer"); preparedStatement.setInt(2, 1000); int rowCount = preparedStatement.executeUpdate(); System.out.println("Record Updated successfully in database. Row Count returned is :: " + rowCount); } catch (SQLException e) { System.out.println("An exception occured while updating data in database. Exception is :: " + e); } } public static Connection getConnection() { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { System.out.println("Error while registering JDBC driver"); return null; } Connection connection = null; try { connection = DriverManager.getConnection(CONNECTION_URL, CONNECTION_USER, CONNECTION_PASSWORD); } catch (SQLException e) { System.out.println("Failed to create Connection"); return null; } System.out.println("Connection created Successfully."); return connection; } } |
Output
1 2 |
Connection created Successfully. Record Updated successfully in database. Row Count returned is :: 2 |