aldesrahim

TugasP15

Dec 24th, 2021 (edited)
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.97 KB | None | 0 0
  1. /**
  2.  * Tugas P15.
  3.  * NPM 202043500047
  4.  * Kelas S3A
  5.  * By Ahmad Al Desrahim (original author)
  6.  *
  7.  * @author Ahmad Al Desrahim
  8.  * @version 1.0.0
  9.  */
  10. import java.sql.*;
  11. import java.util.Scanner;
  12.  
  13. public class Barang {
  14.     Scanner scanner = new Scanner(System.in);
  15.     Connection connection = null;
  16.     PreparedStatement preparedStatement = null;
  17.     ResultSet rs = null;
  18.     String dotDB = "D:/Private/Kuliah/Pemgoraman Sqlite/db_barang.db";
  19.     String leftAlignFormat = "| %-6s | %-13s | %-4s | %-11s |%n";
  20.  
  21.     public static void main(String[] args) {
  22.         Barang v = new Barang();
  23.         v.displayMenu();
  24.     }
  25.  
  26.     public Connection getConnection() throws SQLException {
  27.         // mencegah terjadinya LOCK TABLES SQLITE
  28.         return this.connection != null ? this.connection :DriverManager.getConnection("jdbc:sqlite:" + this.dotDB);
  29.     }
  30.  
  31.     public Statement getStatement() throws SQLException {
  32.         Statement statement;
  33.  
  34.         this.connection = getConnection();
  35.         statement = this.connection.createStatement();
  36.         statement.setQueryTimeout(30);
  37.  
  38.         return statement;
  39.     }
  40.  
  41.     /**
  42.      * Menu utama
  43.      */
  44.     public void displayMenu() {
  45.         this.breakLines(50);
  46.         System.out.println("[1] Lihat data barang");
  47.         System.out.println("[2] Tambah data barang");
  48.         System.out.println("[3] Ubah data barang");
  49.         System.out.println("[4] Hapus data barang");
  50.         System.out.println("[5] Keluar");
  51.         System.out.print(">> ");
  52.  
  53.         showForm(scanner.nextLine());
  54.     }
  55.  
  56.     /**
  57.      * Menu selection
  58.      * @param menu
  59.      */
  60.     public void showForm(String menu) {
  61.         this.breakLines(50);
  62.  
  63.         switch (menu) {
  64.             case "1":
  65.                 this.formShow();
  66.                 break;
  67.             case "2":
  68.                 this.formAdd();
  69.                 break;
  70.             case "3":
  71.                 this.formUpdate();
  72.                 break;
  73.             case "4":
  74.                 this.formDelete();
  75.                 break;
  76.             case "5":
  77.                 return;
  78.             default:
  79.                 this.displayMenu();
  80.                 return;
  81.         }
  82.  
  83.         this.goToMenu();
  84.     }
  85.  
  86.     /**
  87.      * Fungsi untuk mengambil data barang dari DB
  88.      * @param code kode barang yang ingin dicari, biarkan kosong jika ingin mengambil semua data
  89.      * @return boolean
  90.      * @throws SQLException
  91.      */
  92.     public boolean findBarang(String code) throws SQLException {
  93.         String sql = "SELECT * FROM barang";
  94.  
  95.         if (code != "") {
  96.             sql += " WHERE kode_barang = '"+ code +"'";
  97.         }
  98.  
  99.         this.rs = this.getStatement().executeQuery(sql);
  100.         return !this.isRSEmpty();
  101.     }
  102.  
  103.     /**
  104.      * Form Menampilkan barang
  105.      */
  106.     public void formShow() {
  107.         try {
  108.             System.out.println("+--------+---------------+------+-------------+");
  109.             System.out.println("| kode   | nama          | stok | harga       |");
  110.             System.out.println("+--------+---------------+------+-------------+");
  111.  
  112.             if (this.findBarang("")) while(this.rs.next()) {
  113.                 System.out.format(
  114.                         this.leftAlignFormat,
  115.                         this.rs.getString("kode_barang"),
  116.                         this.rs.getString("nama_barang"),
  117.                         this.rs.getString("stok"),
  118.                         this.rs.getString("harga"));
  119.             } else System.out.format("| %-43s |%n", "Data barang kosong");
  120.  
  121.             System.out.println("+--------+---------------+------+-------------+");
  122.         } catch (Exception e) {
  123.             this.exceptionToMenu(e);
  124.         } finally {
  125.             this.rs = null;
  126.         }
  127.     }
  128.  
  129.     /**
  130.      * Form Tambah barang
  131.      */
  132.     public void formAdd() {
  133.         String code = "", name = "", stock = "", price ="";
  134.         boolean codeExists = true,
  135.                 isInputEmpty = true;
  136.  
  137.         try {
  138.             this.connection = this.getConnection();
  139.             this.preparedStatement = this.connection.prepareStatement("INSERT INTO barang(kode_barang,nama_barang,stok,harga) VALUES (?,?,?,?)");
  140.  
  141.             this.formShow();
  142.             System.out.println("\nTambah data baru: ");
  143.  
  144.             while (isInputEmpty) {
  145.                 System.out.print("Kode: ");
  146.                 code = scanner.nextLine();
  147.  
  148.                 isInputEmpty = code.isEmpty();
  149.                 codeExists = this.findBarang(code);
  150.  
  151.                 if (isInputEmpty || codeExists) {
  152.                     System.out.println(isInputEmpty ? "Kode tidak boleh kosong." : codeExists ? "Kode barang sudah ada." : "");
  153.                     isInputEmpty = true;
  154.                 }
  155.             }
  156.             this.preparedStatement.setString(1, code);
  157.  
  158.             isInputEmpty = true;
  159.             while (isInputEmpty) {
  160.                 System.out.print("Nama: "); name = scanner.nextLine();
  161.                 isInputEmpty = name.isEmpty();
  162.                 if (isInputEmpty) System.out.println("Nama tidak boleh kosong.");
  163.             }
  164.             this.preparedStatement.setString(2, name);
  165.  
  166.             isInputEmpty = true;
  167.             while (isInputEmpty) {
  168.                 System.out.print("Stok: ");
  169.                 stock = scanner.nextLine();
  170.                 isInputEmpty = stock.isEmpty();
  171.                 if (isInputEmpty) System.out.println("Stok tidak boleh kosong.");
  172.             }
  173.             this.preparedStatement.setInt(3, Integer.parseInt(stock));
  174.  
  175.             isInputEmpty = true;
  176.             while (isInputEmpty) {
  177.                 System.out.print("Harga: ");
  178.                 price = scanner.nextLine();
  179.                 isInputEmpty = price.isEmpty();
  180.                 if (isInputEmpty) System.out.println("Harga tidak boleh kosong.");
  181.             }
  182.             this.preparedStatement.setDouble(4, Double.parseDouble(price));
  183.  
  184.             this.preparedStatement.executeUpdate();
  185.             this.preparedStatement.close();
  186.  
  187.             System.out.println("Barang " + name + " berhasil ditambah.");
  188.         } catch (Exception e) {
  189.             this.exceptionToMenu(e);
  190.         } finally {
  191.             this.preparedStatement = null;
  192.             this.rs = null;
  193.         }
  194.     }
  195.  
  196.     /**
  197.      * Form Update barang
  198.      */
  199.     public void formUpdate() {
  200.         String code = "", name = "", stock = "", price ="", nameInput = "", stockInput = "", priceInput ="";
  201.         boolean notFound = true;
  202.  
  203.         try {
  204.             this.connection = this.getConnection();
  205.             this.preparedStatement = this.connection.prepareStatement("UPDATE barang SET nama_barang = ?,stok = ?,harga = ? WHERE kode_barang = ?");
  206.  
  207.             this.formShow();
  208.  
  209.             while (notFound) {
  210.                 System.out.print("\nUbah data [masukkan kode barang] >> ");
  211.                 code = scanner.nextLine();
  212.                 notFound = !this.findBarang(code);
  213.  
  214.                 if (!notFound && this.rs.next()) {
  215.                     System.out.println("Anda akan mengubah data berikut ini: ");
  216.  
  217.                     code = this.rs.getString("kode_barang");
  218.                     System.out.println("Kode: " + code);
  219.  
  220.                     name = this.rs.getString("nama_barang");
  221.                     System.out.println("Nama: " + name);
  222.  
  223.                     stock = this.rs.getString("stok");
  224.                     System.out.println("Stok: " + stock);
  225.  
  226.                     price = this.rs.getString("harga");
  227.                     System.out.println("Harga: " + price);
  228.  
  229.                     System.out.print("Apakah anda yakin ? [Y/n] ");
  230.                     notFound = scanner.nextLine().trim().equalsIgnoreCase("n");
  231.                 } else {
  232.                     System.out.println("Barang dengan kode " + code + " tidak dapat ditemukan.");
  233.                 }
  234.             }
  235.  
  236.             System.out.println("\nLangsung enter jika tidak ingin mengubah data.");
  237.             System.out.println("Ketik - jika ingin mengosongkan data.");
  238.             System.out.println("Kode barang tidak bisa diubah.\n");
  239.  
  240.             System.out.print("Nama ["+ name +"]: "); nameInput = scanner.nextLine();
  241.             this.preparedStatement.setString(1, nameInput.isEmpty() ? name : nameInput);
  242.  
  243.             System.out.print("Stok ["+ stock +"]: "); stockInput = scanner.nextLine();
  244.             this.preparedStatement.setInt(2, Integer.parseInt(stockInput.isEmpty() ? stock : stockInput));
  245.  
  246.             System.out.print("Harga ["+ price +"]: "); priceInput = scanner.nextLine();
  247.             this.preparedStatement.setDouble(3, Double.parseDouble(priceInput.isEmpty() ? price : priceInput));
  248.  
  249.             this.preparedStatement.setString(4, code);
  250.  
  251.             this.preparedStatement.executeUpdate();
  252.             this.preparedStatement.close();
  253.  
  254.             System.out.println("Barang dengan kode " + code + " berhasil diubah.");
  255.         } catch (Exception e) {
  256.             this.exceptionToMenu(e);
  257.         } finally {
  258.             this.preparedStatement = null;
  259.             this.rs = null;
  260.         }
  261.     }
  262.  
  263.     /**
  264.      * Form Hapus barang
  265.      */
  266.     public void formDelete() {
  267.         String code = "", name = "", stock = "", price ="";
  268.         boolean notFound = true;
  269.  
  270.         try {
  271.             this.connection = this.getConnection();
  272.             this.preparedStatement = this.connection.prepareStatement("DELETE FROM barang WHERE kode_barang = ?");
  273.  
  274.             this.formShow();
  275.  
  276.             while (notFound) {
  277.                 System.out.print("\nHapus data [masukkan kode barang] >> ");
  278.                 code = scanner.nextLine();
  279.                 notFound = !this.findBarang(code);
  280.  
  281.                 if (!notFound && this.rs.next()) {
  282.                     System.out.println("Anda akan menghapus data berikut ini: ");
  283.  
  284.                     code = this.rs.getString("kode_barang");
  285.                     System.out.println("Kode: " + code);
  286.  
  287.                     name = this.rs.getString("nama_barang");
  288.                     System.out.println("Nama: " + name);
  289.  
  290.                     stock = this.rs.getString("stok");
  291.                     System.out.println("Stok: " + stock);
  292.  
  293.                     price = this.rs.getString("harga");
  294.                     System.out.println("Harga: " + price);
  295.  
  296.                     System.out.print("Apakah anda yakin ? [Y/n] ");
  297.                     notFound = scanner.nextLine().trim().equalsIgnoreCase("n");
  298.                 } else {
  299.                     System.out.println("Barang dengan kode " + code + " tidak dapat ditemukan.");
  300.                 }
  301.             }
  302.  
  303.             this.preparedStatement.setString(1, code);
  304.  
  305.             this.preparedStatement.executeUpdate();
  306.             this.preparedStatement.close();
  307.  
  308.             System.out.println("Barang dengan kode " + code + " berhasil dihapus.");
  309.         } catch (Exception e) {
  310.             this.exceptionToMenu(e);
  311.         } finally {
  312.             this.preparedStatement = null;
  313.             this.rs = null;
  314.         }
  315.     }
  316.  
  317.     /**
  318.      * Prompt untuk kembali ke menu utama, agar user tidak langsung di arahkan ke menu utama
  319.      */
  320.     public void goToMenu() {
  321.         System.out.print("Tekan enter untuk kembali ke menu...\n");
  322.         scanner.nextLine();
  323.         showForm("0");
  324.     }
  325.  
  326.     /**
  327.      * Untuk handle exception agar aplikasi tidak force close
  328.      * @param e
  329.      */
  330.     public void exceptionToMenu(Exception e) {
  331.         System.err.println("Terjadi kesalahan. error: " + e.getMessage());
  332.         this.goToMenu();
  333.     }
  334.  
  335.     /**
  336.      * Cek apakah ResultSet kosong
  337.      * @return boolean
  338.      * @throws SQLException
  339.      */
  340.     public boolean isRSEmpty() throws SQLException {
  341.         return (!this.rs.isBeforeFirst() && this.rs.getRow() == 0) || this.rs == null;
  342.     }
  343.  
  344.     /**
  345.      * Java console ribet buat bikin fungsi clear screen, jadi ini alternatif nya
  346.      * @param howMuch berapa banyak baris yang ingin disisipkan
  347.      */
  348.     public void breakLines(int howMuch) {
  349.         if (howMuch < 1) return;
  350.         for (int i = 0; i < howMuch; i++) System.out.println("\n");
  351.     }
  352. }
  353.  
Add Comment
Please, Sign In to add comment