
// UpdateDB.java
// https://www.sqlitetutorial.net/sqlite-java/update/
// Andrew Davison, ad@coe.psu.ac.th, Nov. 2022

/* Update the name in an existing (id, name) record in 
   the "person" table of names.db. 
   The updated table is printed.

    Usage:
      > compile UpdateDB.java
      > run UpdateDB <id> <new name>
    e.g.
      > run UpdateDB 1 Andy

*/

import java.sql.*;


public class UpdateDB
{

  public static void main(String[] args)
  {
    if (args.length != 2) {
      System.out.println("Usage: java UpdateDB <id> <name>");
      return;
    }
    int id = Integer.parseInt(args[0]);
    String name = args[1];

    try {
      System.out.println("Connecting to names.db");
      Connection conn = DriverManager.getConnection(         
                                     "jdbc:sqlite:names.db");

      System.out.println("Updating record with id = " + id +
                               " to use the name " + name);
      PreparedStatement pstmt = conn.prepareStatement(
                   "UPDATE person SET name = ? WHERE id = ?");
      pstmt.setString(1, name);
      pstmt.setInt(2, 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 UpdateDB class