
// CreateDB.java
// Andrew Davison, ad@coe.psu.ac.th, Nov. 2022

/* Create (or reinitialize) names.db and add three
   records to the "person" table. The table is printed
   at the end.

    Usage:
      > compile CreateDB.java
      > run CreateDB
*/

import java.io.*;
import java.sql.*;


public class CreateDB
{
  public static void main(String[] args)
  {
    if (fileExists("names.db"))
      System.out.println("Reinitializing names.db");
    else
      System.out.println("Creating names.db");

    try {
      System.out.println("Connecting...");
      Connection conn = DriverManager.getConnection(         
                                     "jdbc:sqlite:names.db");
      Statement stmt = conn.createStatement();

      if (DBUtils.hasTable(conn, "person"))
        System.out.println("Reinitializing person table");
      else
        System.out.println("Creating person table");

      stmt.executeUpdate("DROP TABLE if exists person");
      stmt.executeUpdate("CREATE TABLE person (" +
                       "id integer NOT NULL, " +
                       "name string NOT NULL, " +
                       "PRIMARY KEY (id) )" );

      System.out.println("Inserting three records");
      stmt.executeUpdate("insert into person values(1, 'andrew')");
      stmt.executeUpdate("insert into person values(2, 'supatra')");
      stmt.executeUpdate("insert into person values(3, 'john')");

      DBTablePrinter.printTable(conn, "person");
      conn.close();
    }
    catch(SQLException e)
    {  System.out.println(e.getMessage());  }
  }  // end of main()



  private static boolean fileExists(String fnm)
  {
    File f = new File(fnm);
    return (f.exists() && !f.isDirectory());
  }


}  // end of CreateDB class