
// InsertDB.java
// https://www.sqlitetutorial.net/sqlite-java/insert/
// Andrew Davison, ad@coe.psu.ac.th, Nov. 2022

/* Add an (id, name) record to the "person" table of names.db.
   The updated table is printed.

   The use of id as a primary key means that you cannot
   use the same id twice.

    Usage:
      > compile InsertDB.java
      > run InsertDB  <id> <name>
    e.g.
      > run InsertDB 10 "James Bond"
      > run InsertDB 20 "Sherlock Holmes"
      > run InsertDB 30 "Robin Hood"

*/

import java.sql.*;


public class InsertDB
{

  public static void main(String[] args)
  {
    if (args.length != 2) {
      System.out.println("Usage: java InsertDB <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("Inserting record (" + id + ", " +
                                              name + ")");
      PreparedStatement pstmt = conn.prepareStatement(
                         "INSERT INTO person(id,name) VALUES(?,?)");
      pstmt.setInt(1, id);
      pstmt.setString(2, name);
      int result = pstmt.executeUpdate();
      if (result == 0)
        System.out.println("Insertion failed");
      else
        DBTablePrinter.printTable(conn, "person");

      conn.close();
    }
    catch(SQLException e)
    {  System.out.println(e.getMessage());  }
  } /* main */


}  // end of InsertDB class