Belajar CRUD JavaFX - Tutorial Bahasa Indonesia

Belajar CRUD JavaFX - Tutorial Bahasa Indonesia

Coding Koneksi


public Connection getConnection(){
        Connection conn;
        try{
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/perpus", "root","");
            return conn;
        }catch(Exception ex){
            System.out.println("Error: " + ex.getMessage());
            return null;
        }
    }

Coding Menampilkan data Buku


 public ObservableList getBukuList(){
        ObservableList bookList = FXCollections.observableArrayList();
        Connection conn = getConnection();
        String query = "SELECT * FROM buku";
        Statement st;
        ResultSet rs;
        
        try{
            st = conn.createStatement();
            rs = st.executeQuery(query);
            Buku buku;
            while(rs.next()){
                buku = new Buku(rs.getInt("id"), 
                        rs.getString("judul"), rs.getString("pengarang"), 
                        rs.getInt("tahun"),rs.getInt("halaman"));
                bookList.add(buku);
            }
                
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return bookList;
    }
    
    public void showBuku() {
        ObservableList list = getBukuList();
        colkode.setCellValueFactory(new PropertyValueFactory("kode"));
        coljudul.setCellValueFactory(new PropertyValueFactory("judul"));
        colpengarang.setCellValueFactory(new PropertyValueFactory("pengarang"));
        coltahun.setCellValueFactory(new PropertyValueFactory("tahun"));
        colhalaman.setCellValueFactory(new PropertyValueFactory("halaman"));
        tvBuku.setItems(list);

    }

Coding executeQuery


  private void executeQuery(String query) {
        Connection conn = getConnection();
        Statement st;
        try{
            st = conn.createStatement();
            st.executeUpdate(query);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

Simpan Data


    private void insertRecord(){
        String query = "INSERT INTO buku VALUES (" + tfId.getText() + ",'" + tfJudul.getText() + "','" + tfPengarang.getText() + "',"
                + tftahun.getText() + "," + tfHalaman.getText() + ")";
        executeQuery(query);
        showbuku();
    }

Ubah Data


    private void updateRecord(){
        String query = "UPDATE  buku SET judul  = '" + tfJudul.getText() + "', pengarang = '" + tfPengarang.getText() + "', tahun = " +
                tftahun.getText() + ", halaman = " + tfHalaman.getText() + " WHERE id = " + tfId.getText() + "";
        executeQuery(query);
        showbuku();
    }

Hapus Data


    private void deleteButton(){
        String query = "DELETE FROM buku WHERE id =" + tfId.getText() + "";
        executeQuery(query);
        showbuku();
    }