JDBC Tutorial - JDBC Delete Record








The following code shows how to delete records from a table.

It issues the delete sql command.

DELETE FROM Person WHERE id = 1

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
//  w  w  w  .j  a  v a 2  s.co m
public class Main {
  static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

  static final String USER = "username";
  static final String PASS = "password";

  public static void main(String[] args) throws Exception {
    Connection conn = null;
    Statement stmt = null;

    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    System.out.println("Deleting database...");
    stmt = conn.createStatement();

    conn = DriverManager.getConnection(DB_URL, USER, PASS);

    stmt = conn.createStatement();

    String sql = "DELETE FROM Person WHERE id = 1";
    stmt.executeUpdate(sql);
    stmt.close();
    conn.close();
  }
}




Example PreparedStatement

The following code shows how to delete a record with PreparedStatement by using the Oracle JDBC Driver.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/*www .j  av  a  2 s .c om*/
public class Main {
  private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
  private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:YourDatabase";
  private static final String DB_USER = "user";
  private static final String DB_PASSWORD = "password";

  public static void main(String[] argv) throws Exception {
    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;
    Class.forName(DB_DRIVER);
    dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
        DB_PASSWORD);
    String deleteSQL = "DELETE Person WHERE USER_ID = ?";
    preparedStatement = dbConnection.prepareStatement(deleteSQL);
    preparedStatement.setInt(1, 1001);

    preparedStatement.executeUpdate();
    preparedStatement.close();
    dbConnection.close();

  }
}