JDBC update prepared statement example
In this example we will show how to update a row in a MYSQL
DB table using JDBC PreparedStatement
.
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;public class InsertRow { private static final String UPDATE_ROW_SQL = "UPDATE WORLD.STUDENT SET ROLL_NUMBER = ?" + "WHERE ID = ?"; public static void main(String[] args) { try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "root", "root"); PreparedStatement preparedStatement = con.prepareStatement(UPDATE_ROW_SQL)) { preparedStatement.setInt(1, 20); preparedStatement.setInt(2, 1); int row = preparedStatement.executeUpdate(); System.out.println("affected rows " + row); System.out.println("Row updated succesfully"); } catch (SQLException e) { System.out.println(e); } }}
Console Output :
affected rows 1Row updated succesfully
Update a row using a Statment instance
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;public class InsertRow { private static final String UPDATE_ROW_SQL = "UPDATE WORLD.STUDENT SET ROLL_NUMBER = 30" + "WHERE ID = 2"; public static void main(String[] args) { try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "root", "root"); Statement statement = con.createStatement()) { statement.execute(UPDATE_ROW_SQL); System.out.println("Row updated succesfully"); } catch (SQLException e) { System.out.println(e); } }}
Console Output :
Row updated succesfully