
// StoreImage.java
// https://www.w3schools.blog/store-image-in-database-in-java
// Andrew Davison, ad@coe.psu.ac.th, Nov. 2022

/* Store an image in the "pics" table of pictures.db 
   as the record (id, BLOB) by supplying the name of the file.

   The file name without its extension becomes the id, and the
   BLOB is the binary representation of the loaded image.

   The id field is unique in the "pics" table, and so it is
   not possible to use the same id twice.

   The updated table is printed at the end.

    Usage:
      > compile StoreImage.java
      > run StoreImage <fnm>
    e.g.
      > run StoreImage "cat.png"
*/


import java.io.*;
import java.sql.*;


public class StoreImage
{
  public static void main(String args[])
  {
    if (args.length != 1) {
      System.out.println("Usage: java StoreImage <image fnm>");
      System.exit(1);
    }
    String imFnm = args[0];

    try{
      System.out.println("Connecting to pictures.db");
      Connection conn = DriverManager.getConnection(
                                "jdbc:sqlite:pictures.db");
      PreparedStatement ps =
          conn.prepareStatement("insert into pics values (?,?)");

      FileInputStream fis =
                  new FileInputStream(imFnm);
      String id = stripExt(imFnm);
      ps.setString(1, id);
      ps.setBinaryStream(2, fis, fis.available());

      int result = ps.executeUpdate();
      if (result == 0)
        System.out.println("Insertion failed");
      else
        System.out.println(imFnm + " stored with id = " + id);

      DBTablePrinter.printTable(conn, "pics");
      conn.close();
    }
    catch(Exception e)
    {  System.out.println(e.getMessage());  }
  } /* main */



  private static String stripExt(String fnm)
  {
    int dotPos = fnm.lastIndexOf('.');
    if (dotPos == -1)
      return fnm;
    else
      return fnm.substring(0, dotPos);
  }

}  // end of StoreImage class