Delete Record using JDBC Statement

This example about, How to Delete Record using JDBC Statement in Java

Table Information

1. Table Query

CREATE TABLE customer (customerId INT, customerName VARCHAR(30), customerAge INT, customerAddress VARCHAR(60), PRIMARY KEY(customerId));

2. Table Structure

Delete Record using JDBC Statement

Project Structure

Delete Record using JDBC Statement

DeleteRecord.java

package com.dineshkrish.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 
* @author Dinesh Krishnan
* 
*/
public class DeleteRecord {
// Method to get Connection from Database
public static Connection getConnection() {
Connection connection = null;
try {
// Loading the Driver
Class.forName("com.mysql.jdbc.Driver");
// Getting the Database Connection passing URL, Username and Password
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/dineshkrish", "root", "");
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return connection;
}
// Method to Delete record from Database
public static boolean doDelete(int customerId) {
try {
// Getting Connection for Database
Connection connection = getConnection();
// Delete Query
final String DELETE_QUERY = "DELETE FROM customer WHERE customerId = "+ customerId +" ";
Statement statement = connection.createStatement();
// Executing Query to perform Delete Operation
statement.execute(DELETE_QUERY);
return true;
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
// Calling Method to perform Delete Operation
boolean status = DeleteRecord.doDelete(101);
// Printing the Result based on the Status
if (status) {
System.out.println("Record Deleted Successfully...");
} else {
System.out.println("Application Error Occured");
}
}
}

Output

Record Deleted Successfully…

Download Source Code

Download Here

References

1. Java SQL Documentation
2. Java SQL Connection API
3. Java Statement API

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *