JDBC Statement – Delete Record Example
A JDBC statement object is used to send SQL command(s) to your relational database management system (RDBMS). It is associated with an open connection to the database and may not be created without one. In this example, we will delete a record in the employee table using executeUpdate() method.
Common Methods used with Statements
Method Name | Description |
---|---|
addBatch(String sql) | Adds the given SQL to the current list of SQL commmands for this Statement object |
execute(String sql) | Executes the given SQL statement, which may return multiple results |
executeBatch() | Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts |
executeQuery(String sql) | Executes the given SQL statement, which returns a single ResultSet object |
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 |
Creating a Statement Object
statement = connection.createStatement(); statement.executeUpdate(sql);
Full Program Listing
package com.avaldes.tutorials; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCStatementDeleteRecordExample { public static void main(String[] args) throws SQLException { String database_url = "jdbc:sqlserver://localhost:1433;databaseName=tutorial"; String username = "webuser"; String password = "webuser123"; Connection connection = null; Statement statement = null; ResultSet result = null; String sql = null; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (ClassNotFoundException e) { System.out.println("ERROR: Unable to load SQLServer JDBC Driver"); e.printStackTrace(); return; } try { connection = DriverManager.getConnection(database_url, username, password); } catch (SQLException e) { System.out.println("ERROR: Unable to establish a connection with the database!"); e.printStackTrace(); return; } System.out.println("Trying to delete a record using statement..."); try { if (connection != null) { statement = connection.createStatement(); sql = "DELETE from dbo.employee " + "WHERE employee_id = 10"; statement.executeUpdate(sql); System.out.println(sql); System.out.println("Deleted record in employee table..."); } else { System.out.println("ERROR: Unable to make a database connection!"); } } catch (SQLException e) { e.printStackTrace(); return; } finally { System.out.println("Closing connection..."); if (connection != null) connection.close(); } } }
Employee Table — Before Delete

Employee Table — After Delete

Output

Trying to delete a record using statement... DELETE from dbo.employee WHERE employee_id = 10 Deleted record in employee table... Closing connection...
Please Share Us on Social Media






Leave a Reply