Deleting a Row from a Database Table - Java JDBC

Java examples for JDBC:SQL Statement

Description

Deleting a Row from a Database Table

Demo Code

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Connection connection = null;
    Statement stmt = connection.createStatement();

    // Prepare a statement to insert a record
    String sql = "DELETE FROM my_table WHERE col_string='a string'";
    // Execute the delete statement
    int deleteCount = stmt.executeUpdate(sql);
    // deleteCount contains the number of deleted rows

    // Use a prepared statement to delete

    // Prepare a statement to delete a record
    sql = "DELETE FROM my_table WHERE col_string=?";
    PreparedStatement pstmt = connection.prepareStatement(sql);
    // Set the value
    pstmt.setString(1, "a string");
    deleteCount = pstmt.executeUpdate();
  }//from w w  w  .  j  a  va  2 s .  co m
}

Related Tutorials