We saw how to Create a table and Insert Data using Statement in Java.
Now lets delete some of the data from the table using Statement.
Delete record SQL
Below is the query that can be fired directly on database to delete record.
1 2 |
DELETE FROM employee_details WHERE designation = 'Engineer'; |
Method from Statement Interface used
1 |
int executeUpdate(String sql) |
“Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.”
In case of Deleting records, executeUpdate(String sql) returns the total number of records that where deleted using the Delete SQL statement.
Now lets see the sample code for firing this SQL using JDBC
Example : Delete record using Statement in Java
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 |
package com.kscodes.sampleproject.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class StatementDeleteExample { 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 = "DELETE FROM employee_details " + " WHERE designation = 'Engineer';"; try (Connection connection = getConnection(); Statement statement = connection.createStatement()) { int rowCount = statement.executeUpdate(updateSql); System.out.println("Record Deleted successfully from database. Total records deleted are :: " + rowCount); } catch (SQLException e) { System.out.println("An exception occured while Deleting records from Table. 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 Deleted successfully from database. Total records deleted are :: 2 |
Now if we try to re-run the code, since no records will be deleted for the same criteria, the return value of
executeUpdate(String sql) will be 0.
Since we have JDK 7, we are using Try-with-resources Statement to handle the resources that are opened.