
// DeleteDB.java
// https://www.sqlitetutorial.net/sqlite-java/delete/
// Andrew Davison, ad@coe.psu.ac.th, Nov. 2022

/* Delete an (id, name) record from the "person" table 
   of names.db based on the id, which is unique. 
   The updated table is printed.

    Usage:
      > compile DeleteDB.java
      > run DeleteDB <id>
    e.g.
      > run DeleteDB 1
*/

import java.sql.*;


public class DeleteDB
{

  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: java DeleteDB <id in names.db>");
      return;
    }
    int id = Integer.parseInt(args[0]);

    try {
      System.out.println("Connecting to names.db");
      Connection conn = DriverManager.getConnection(         
                                     "jdbc:sqlite:names.db");

      System.out.println("Deleting record using id = " + id);
      PreparedStatement pstmt = conn.prepareStatement(
                         "DELETE FROM person WHERE id = ?");
      pstmt.setInt(1, id);
      int result = pstmt.executeUpdate();
      if (result == 0)
        System.out.println("No suitable record found");
      else
        DBTablePrinter.printTable(conn, "person");

      conn.close();
    }
    catch(SQLException e)
    {  System.out.println(e.getMessage());  }
  } /* main */


}  // end of DeleteDB class