Anonymous
Соединение отказано: HTML Backend FrondTend
Сообщение
Anonymous » 11 апр 2025, 23:01
"Привет, не могли бы вы помочь мне выяснить, почему это не работает? Я уже пробовал несколько вещей, но независимо от того, что я делаю, это все еще не функционирует должным образом, и я не уверен, что мне не хватает». />
felvetel-komponens: < /strong> < /p>
Код: Выделить всё
import React, { useState } from "react";
const BookFelvetel = () => {
const [book, setBook] = useState({
title: "",
author: "",
publish_year: "",
page_count: 0
});
const [error, setError] = useState("");
const [success, setSuccess] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setError("");
setSuccess(false);
try {
const response = await fetch("http://localhost:3000/api/books", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(book),
});
if (!response.ok) {
const errorDetails = await response.json();
setError("A könyvek felvétele sikertelen: " + errorDetails.message.join(", ") );
setSuccess(false);
}
if (response.ok) {
setSuccess(true);
setBook({
title: "",
author: "",
publish_year: "",
page_count: 0
});
}
} catch (err) {
setSuccess(false);
setError("A felvétele sikertelen!");
}
};
const handleInputChangeTitle = (e) => { setBook({ ...book, title: e.target.value }); };
const handleInputChangeAuthor = (e) => { setBook({ ...book, author: e.target.value }); };
const handleInputChangeYear = (e) => { setBook({ ...book, publish_year: Number(e.target.value) }); };
const handleInputChangePageCount = (e) => { setBook({ ...book, page_count: Number(e.target.value) }); };
return (
Könyv felvétele
{success &&
Sikeres felvétel!
}
{error &&
{error}
}
Title
Author
Publish Year
Page Count
Könyv felvétele
);
};
export default BookFelvetel;
Компонент списка [/b]
Код: Выделить всё
import React, { useEffect, useState } from "react";
const BooksList = () => {
const [books, setBooks] = useState([]);
const [error, setError] = useState("");
useEffect(() => {
const fetchBooks = async () => {
try {
const response = await fetch("http://localhost:3000/api/books");
if (!response.ok) {
setError("A könyvek betöltése sikertelen (" + response.statusText + ")!");
return;
}
const data = await response.json();
setBooks(data);
} catch (err) {
setError(`A könyvek betöltése sikertelen ${err}!`);
}
};
fetchBooks();
}, []);
const handleRent = async (id) => {
try {
const response = await fetch(`http://localhost:3000/api/books/${id}/rent`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
setError(`Hiba történt: ${response.statusText}`);
} else {
setError(`Sikeres a könyv kölcsönzése. ${response.statusText}`);
}
} catch (err) {
setError(`Failed to rent the book (${err}).`);
}
};
return (
Könyvek listája
{error &&
{error}
}
{books.length === 0 &&
Nincs elérhető könyv a listában.
}
{books.map((book) => (
{book.title}
Author: {book.author}
{book.publish_year}
{book.page_count}
[img]{`${book.author}.jpg`}
className="img-fluid mb-3"
/>
handleRent(book.id)} className="btn btn-primary mb-3">Kölcsönöz
))}
);
};
export по умолчанию Bookslist;
App.tsx
Код: Выделить всё
import { useState } from 'react';
import './App.css';
import Bookfelvetel from './components/Bookfelvetel';
import Booklist from './components/Booklist';
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
const [activeSection, setActiveSection] = useState('lista');
return (
Petrik Könyv nyilvántartó
[url=https://www.petrik.hu]Petrik[/url]
{activeSection === 'lista' && }
{activeSection === 'felvetel' && }
{activeSection !== 'lista' && activeSection !== 'felvetel' && }
Az oldalt készítette: Gipsz Jakab, 2025.
);
}
export default App;
< /code>
[b] backend < /strong> < /p>
shrong>schema.prisma[/b]
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model books {
id Int @id @default(autoincrement())
title String @db.VarChar(255)
author String @db.VarChar(255)
publish_year Int
page_count Int
rentals rentals[]
}
model rentals {
id Int @id @default(autoincrement())
book books @relation(fields: [book_id], references: [id])
book_id Int
start_date DateTime
end_date DateTime
}
books.controller.ts
Код: Выделить всё
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { BooksService } from './books.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
@Controller('api/books')
export class BooksController {
constructor(private readonly booksService: BooksService) {}
@Post()
create(@Body() createBookDto: CreateBookDto) {
return this.booksService.create(createBookDto);
}
@Get()
findAll() {
return this.booksService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.booksService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateBookDto: UpdateBookDto) {
return this.booksService.update(+id, updateBookDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.booksService.remove(+id);
}
@Post(':id/rent')
rent(@Param('id') id: string) {
return this.booksService.rent(+id);
}
}
books.service.ts
Код: Выделить всё
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { PrismaService } from 'src/prisma.service';
@Injectable()
export class BooksService {
constructor(private readonly db: PrismaService) {
}
create(createBookDto: CreateBookDto) {
return this.db.books.create({
data: createBookDto
})
}
findAll() {
return this.db.books.findMany({
select: {
id: true,
title: true,
author: true,
publish_year: true,
page_count: true,
},
});
}
async rent(id: number) {
let book = await this.db.books.findFirst({ where: { id } });
if (!book) throw new NotFoundException('Nincs ilyen könyv');
const current_date = new Date();
let rental = await this.db.rentals.findFirst({
where: {
book_id: id,
start_date: {
lt: current_date
},
end_date: {
gt: current_date
}
}
})
if (rental) {
throw new ConflictException("A könyv már foglalt");
}
const end_date = new Date();
end_date.setDate(current_date.getDate() + 7);
return this.db.rentals.create({
data: {
book_id: id,
start_date: current_date,
end_date,
}
})
}
findOne(id: number) {
return `This action returns a #${id} book`;
}
update(id: number, updateBookDto: UpdateBookDto) {
return `This action updates a #${id} book`;
}
remove(id: number) {
return `This action removes a #${id} book`;
}
}
main.ts
Код: Выделить всё
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: false,
optionsSuccessStatus: 204,
});
app.useGlobalPipes(new ValidationPipe());
app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('ejs');
await app.listen(3000);
}
bootstrap();
prisma.service.ts
Код: Выделить всё
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}
}
java
book.java
Код: Выделить всё
package com.example.konyvtarasztali;
public class Book {
private int id;
private String title;
private String author;
private int publish_year;
private int page_count;
public Book(int id, String title, String author, int publish_year, int page_count) {
this.id = id;
this.title = title;
this.author = author;
this.publish_year = publish_year;
this.page_count = page_count;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getPublish_year() {
return publish_year;
}
public int getPage_count() {
return page_count;
}
}
bookservice.java
Код: Выделить всё
package com.example.konyvtarasztali;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BookService {
public static final String DB_DRIVER = "mysql";
public static final String DB_HOST = "localhost";
public static final String DB_PORT = "3306";
public static final String DB_DBNAME = "vizsga-2023";
public static final String DB_USER = "root";
public static final String DB_PASSWORD = "";
private final Connection connection;
public BookService() throws SQLException {
String url = String.format("jdbc:%s://%s:%s/%s", DB_DRIVER, DB_HOST, DB_PORT, DB_DBNAME);
connection = DriverManager.getConnection(url, DB_USER, DB_PASSWORD);
}
public List getAll() throws SQLException {
List books = new ArrayList();
String sql = "SELECT * FROM books";
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(sql);
while (result.next()) {
int id = result.getInt("id");
String title = result.getString("title");
String author = result.getString("author");
int publish_year = result.getInt("publish_year");
int page_count = result.getInt("page_count");
Book book = new Book(id, title, author, publish_year, page_count);
books.add(book);
}
return books;
}
public boolean delete(Book book) throws SQLException {
String sql = "DELETE FROM books WHERE id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setInt(1, book.getId());
return stmt.executeUpdate() == 1;
}
}
hellocontroller
Код: Выделить всё
package com.example.konyvtarasztali;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import java.sql.SQLException;
import java.util.Optional;
public class HelloController {
@FXML
private TableView bookTable;
@FXML
private TableColumn titleCol;
@FXML
private TableColumn authorCol;
@FXML
private TableColumn publish_yearCol;
@FXML
private TableColumn page_countCol;
private BookService bookService;
public void initialize() {
titleCol.setCellValueFactory(new PropertyValueFactory("title"));
authorCol.setCellValueFactory(new PropertyValueFactory("author"));
publish_yearCol.setCellValueFactory(new PropertyValueFactory("publish_year"));
page_countCol.setCellValueFactory(new PropertyValueFactory("page_count"));
try {
bookService = new BookService();
refreshBooks();
} catch (SQLException e) {
Platform.runLater(() -> {
alert(Alert.AlertType.ERROR,
"Nem sikerült kapcsolódni az adatbázishoz. Az alkalmazás leáll",
e.getMessage());
Platform.exit();
});
}
}
private static Optional alert(Alert.AlertType alertType, String headerText) {
return alert(alertType, headerText, "");
}
private static Optional alert(Alert.AlertType alertType, String headerText, String contentText) {
Alert alert = new Alert(alertType);
alert.setHeaderText(headerText);
alert.setContentText(contentText);
return alert.showAndWait();
}
private void refreshBooks() throws SQLException {
bookTable.getItems().clear();
bookTable.getItems().addAll(bookService.getAll());
}
@FXML
public void deleteClick() {
Book selected = bookTable.getSelectionModel().getSelectedItem();
if (selected == null) {
alert(Alert.AlertType.WARNING, "Törléshez előbb válasszon ki könyvet");
return;
}
Optional selectedButton = alert(Alert.AlertType.CONFIRMATION,
"Biztos szeretné törölni a kiválasztott könyvet?");
if (selectedButton.isPresent() && selectedButton.get().equals(ButtonType.OK)) {
deleteBook(selected);
}
}
private void deleteBook(Book book) {
try {
if (bookService.delete(book)) {
alert(Alert.AlertType.INFORMATION, "Sikeres törlés");
} else {
alert(Alert.AlertType.WARNING, "Sikertelen törlés",
"A könyv már korábban törölve lett");
}
refreshBooks();
} catch (SQLException e) {
alert(Alert.AlertType.ERROR, "Hiba történt a törlés során", e.getMessage());
}
}
}
main
Код: Выделить всё
package com.example.konyvtarasztali;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
if (Arrays.asList(args).contains("--stat")) {
Statisztika.main(args);
} else {
HelloApplication.main(args);
}
}
}
Статистика
Код: Выделить всё
package com.example.konyvtarasztali;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
public class Statisztika {
private Statisztika() {}
private static List books;
public static void main(String[] args) {
try {
readBooksFromDatabase();
System.out.printf("500 oldalnál hosszabb könyvek száma: %d\n", countLongerThan500Pages());
System.out.printf("%s 1950-nél régebbi könyv\n", isOlderThan1950Present()? "Van" : "Nincs");
Book longest = getLongest();
System.out.printf("A leghosszabb könyv:\n" +
"\tSzerző: %s\n" +
"\tCím: %s\n" +
"\tKiadás éve: %d\n" +
"\tOldalszám: %d\n", longest.getAuthor(), longest.getTitle(),
longest.getPublish_year(), longest.getPage_count());
System.out.printf("A legtöbb könyvvel rendelkező szerző: %s\n", getAuthorWithMostBooks());
String title = readFromConsole();
printAuthor(title);
} catch (SQLException e) {
System.err.println("Nem sikerült csatlakozni az adatbázishoz, az alkalmazás leáll!");
System.out.println(e.getMessage());
}
}
private static void printAuthorStream(String title) {
Optional optionalKonyv =
books.stream().filter(book -> book.getTitle().equals(title)).findFirst();
if (optionalKonyv.isPresent()) {
System.out.printf("A megadott könyv szerzője %s\n", optionalKonyv.get().getAuthor());
} else {
System.out.println("Nincs ilyen könyv");
}
}
private static void printAuthor(String title) {
int ind = 0;
while (ind < books.size() && !books.get(ind).getTitle().equals(title)) {
ind++;
}
if (ind < books.size()) {
System.out.printf("A megadott könyv szerzője %s\n", books.get(ind).getAuthor());
} else {
System.out.println("Nincs ilyen könyv");
}
}
private static String readFromConsole() {
Scanner sc = new Scanner(System.in);
System.out.print("Adjon meg egy könyv címet: ");
return sc.nextLine();
}
private static String getAuthorWithMostBooksStream() {
return books.stream()
// Csoportosítás, a létrejött map kulcs-érték: szerző(string)-rekordszám(long)
.collect(Collectors.groupingBy(Book::getAuthor, Collectors.counting()))
.entrySet().stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.get()
.getKey();
}
private static String getAuthorWithMostBooks() {
Map authorBookCounts = new HashMap();
for (Book book: books) {
authorBookCounts.putIfAbsent(book.getAuthor(), 0L);
long count = authorBookCounts.get(book.getAuthor());
authorBookCounts.put(book.getAuthor(), count + 1);
}
String authorWithMostBooks = "";
long maxBookCount = 0;
for (Map.Entry authorBookCount: authorBookCounts.entrySet()) {
if (authorBookCount.getValue() > maxBookCount) {
authorWithMostBooks = authorBookCount.getKey();
maxBookCount = authorBookCount.getValue();
}
}
return authorWithMostBooks;
}
private static Book getLongestStream() {
return books.stream().max(Comparator.comparingInt(Book::getPage_count)).get();
}
private static Book getLongest() {
Book longest = books.get(0);
for (int i = 1; i < books.size(); i++) {
if (books.get(i).getPage_count() > longest.getPage_count()) {
longest = books.get(i);
}
}
return longest;
}
private static boolean isOlderThan1950PresentStream() {
return books.stream().anyMatch(book -> book.getPublish_year() < 1950);
}
private static boolean isOlderThan1950Present() {
int ind = 0;
while (ind < books.size() && !(books.get(ind).getPublish_year() < 1950)) {
ind++;
}
return ind < books.size();
}
private static long countLongerThan500PagesWithStream() {
return books.stream().filter(book -> book.getPage_count() > 500).count();
}
private static long countLongerThan500Pages() {
long count = 0;
for (Book book: books) {
if (book.getPage_count() > 500) {
count++;
}
}
return count;
}
private static void readBooksFromDatabase() throws SQLException {
BookService db = new BookService();
books = db.getAll();
}
}
hello-view
< /code>
, чтобы решить задачу, но я не могу ее получить, потому что я шик>
Подробнее здесь:
https://stackoverflow.com/questions/795 ... -frondtend
1744401711
Anonymous
"Привет, не могли бы вы помочь мне выяснить, почему это не работает? Я уже пробовал несколько вещей, но независимо от того, что я делаю, это все еще не функционирует должным образом, и я не уверен, что мне не хватает». /> [b] felvetel-komponens: < /strong> < /p> [code] import React, { useState } from "react"; const BookFelvetel = () => { const [book, setBook] = useState({ title: "", author: "", publish_year: "", page_count: 0 }); const [error, setError] = useState(""); const [success, setSuccess] = useState(false); const handleSubmit = async (e) => { e.preventDefault(); setError(""); setSuccess(false); try { const response = await fetch("http://localhost:3000/api/books", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(book), }); if (!response.ok) { const errorDetails = await response.json(); setError("A könyvek felvétele sikertelen: " + errorDetails.message.join(", ") ); setSuccess(false); } if (response.ok) { setSuccess(true); setBook({ title: "", author: "", publish_year: "", page_count: 0 }); } } catch (err) { setSuccess(false); setError("A felvétele sikertelen!"); } }; const handleInputChangeTitle = (e) => { setBook({ ...book, title: e.target.value }); }; const handleInputChangeAuthor = (e) => { setBook({ ...book, author: e.target.value }); }; const handleInputChangeYear = (e) => { setBook({ ...book, publish_year: Number(e.target.value) }); }; const handleInputChangePageCount = (e) => { setBook({ ...book, page_count: Number(e.target.value) }); }; return ( Könyv felvétele {success && Sikeres felvétel! } {error && {error} } Title Author Publish Year Page Count Könyv felvétele ); }; export default BookFelvetel; [/code] Компонент списка [/b] [code] import React, { useEffect, useState } from "react"; const BooksList = () => { const [books, setBooks] = useState([]); const [error, setError] = useState(""); useEffect(() => { const fetchBooks = async () => { try { const response = await fetch("http://localhost:3000/api/books"); if (!response.ok) { setError("A könyvek betöltése sikertelen (" + response.statusText + ")!"); return; } const data = await response.json(); setBooks(data); } catch (err) { setError(`A könyvek betöltése sikertelen ${err}!`); } }; fetchBooks(); }, []); const handleRent = async (id) => { try { const response = await fetch(`http://localhost:3000/api/books/${id}/rent`, { method: "POST", headers: { "Content-Type": "application/json", }, }); if (!response.ok) { setError(`Hiba történt: ${response.statusText}`); } else { setError(`Sikeres a könyv kölcsönzése. ${response.statusText}`); } } catch (err) { setError(`Failed to rent the book (${err}).`); } }; return ( Könyvek listája {error && {error} } {books.length === 0 && Nincs elérhető könyv a listában. } {books.map((book) => ( {book.title} Author: {book.author} {book.publish_year} {book.page_count} [img]{`${book.author}.jpg`} className="img-fluid mb-3" /> handleRent(book.id)} className="btn btn-primary mb-3">Kölcsönöz ))} ); }; [/code] export по умолчанию Bookslist; [b] App.tsx[/b] [code] import { useState } from 'react'; import './App.css'; import Bookfelvetel from './components/Bookfelvetel'; import Booklist from './components/Booklist'; import 'bootstrap/dist/css/bootstrap.min.css'; function App() { const [activeSection, setActiveSection] = useState('lista'); return ( Petrik Könyv nyilvántartó [url=https://www.petrik.hu]Petrik[/url] {activeSection === 'lista' && } {activeSection === 'felvetel' && } {activeSection !== 'lista' && activeSection !== 'felvetel' && } Az oldalt készítette: Gipsz Jakab, 2025. ); } export default App; < /code> [b] backend < /strong> < /p> shrong>schema.prisma[/b] generator client { provider = "prisma-client-js" } datasource db { provider = "mysql" url = env("DATABASE_URL") } model books { id Int @id @default(autoincrement()) title String @db.VarChar(255) author String @db.VarChar(255) publish_year Int page_count Int rentals rentals[] } model rentals { id Int @id @default(autoincrement()) book books @relation(fields: [book_id], references: [id]) book_id Int start_date DateTime end_date DateTime } [/code] [b] books.controller.ts[/b] [code] import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; import { BooksService } from './books.service'; import { CreateBookDto } from './dto/create-book.dto'; import { UpdateBookDto } from './dto/update-book.dto'; @Controller('api/books') export class BooksController { constructor(private readonly booksService: BooksService) {} @Post() create(@Body() createBookDto: CreateBookDto) { return this.booksService.create(createBookDto); } @Get() findAll() { return this.booksService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.booksService.findOne(+id); } @Patch(':id') update(@Param('id') id: string, @Body() updateBookDto: UpdateBookDto) { return this.booksService.update(+id, updateBookDto); } @Delete(':id') remove(@Param('id') id: string) { return this.booksService.remove(+id); } @Post(':id/rent') rent(@Param('id') id: string) { return this.booksService.rent(+id); } } [/code] [b] books.service.ts[/b] [code] import { ConflictException, Injectable, NotFoundException } from '@nestjs/common'; import { CreateBookDto } from './dto/create-book.dto'; import { UpdateBookDto } from './dto/update-book.dto'; import { PrismaService } from 'src/prisma.service'; @Injectable() export class BooksService { constructor(private readonly db: PrismaService) { } create(createBookDto: CreateBookDto) { return this.db.books.create({ data: createBookDto }) } findAll() { return this.db.books.findMany({ select: { id: true, title: true, author: true, publish_year: true, page_count: true, }, }); } async rent(id: number) { let book = await this.db.books.findFirst({ where: { id } }); if (!book) throw new NotFoundException('Nincs ilyen könyv'); const current_date = new Date(); let rental = await this.db.rentals.findFirst({ where: { book_id: id, start_date: { lt: current_date }, end_date: { gt: current_date } } }) if (rental) { throw new ConflictException("A könyv már foglalt"); } const end_date = new Date(); end_date.setDate(current_date.getDate() + 7); return this.db.rentals.create({ data: { book_id: id, start_date: current_date, end_date, } }) } findOne(id: number) { return `This action returns a #${id} book`; } update(id: number, updateBookDto: UpdateBookDto) { return `This action updates a #${id} book`; } remove(id: number) { return `This action removes a #${id} book`; } } [/code] [b] main.ts[/b] [code] import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { NestExpressApplication } from '@nestjs/platform-express'; import { join } from 'path'; import { ValidationPipe } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors({ origin: '*', methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS', preflightContinue: false, optionsSuccessStatus: 204, }); app.useGlobalPipes(new ValidationPipe()); app.useStaticAssets(join(__dirname, '..', 'public')); app.setBaseViewsDir(join(__dirname, '..', 'views')); app.setViewEngine('ejs'); await app.listen(3000); } bootstrap(); [/code] [b] prisma.service.ts[/b] [code] import { Injectable, OnModuleInit } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit { async onModuleInit() { await this.$connect(); } } [/code] [b] java [/b] [b]book.java[/b] [code] package com.example.konyvtarasztali; public class Book { private int id; private String title; private String author; private int publish_year; private int page_count; public Book(int id, String title, String author, int publish_year, int page_count) { this.id = id; this.title = title; this.author = author; this.publish_year = publish_year; this.page_count = page_count; } public int getId() { return id; } public String getTitle() { return title; } public String getAuthor() { return author; } public int getPublish_year() { return publish_year; } public int getPage_count() { return page_count; } } [/code] [b] bookservice.java[/b] [code] package com.example.konyvtarasztali; import java.sql.*; import java.util.ArrayList; import java.util.List; public class BookService { public static final String DB_DRIVER = "mysql"; public static final String DB_HOST = "localhost"; public static final String DB_PORT = "3306"; public static final String DB_DBNAME = "vizsga-2023"; public static final String DB_USER = "root"; public static final String DB_PASSWORD = ""; private final Connection connection; public BookService() throws SQLException { String url = String.format("jdbc:%s://%s:%s/%s", DB_DRIVER, DB_HOST, DB_PORT, DB_DBNAME); connection = DriverManager.getConnection(url, DB_USER, DB_PASSWORD); } public List getAll() throws SQLException { List books = new ArrayList(); String sql = "SELECT * FROM books"; Statement stmt = connection.createStatement(); ResultSet result = stmt.executeQuery(sql); while (result.next()) { int id = result.getInt("id"); String title = result.getString("title"); String author = result.getString("author"); int publish_year = result.getInt("publish_year"); int page_count = result.getInt("page_count"); Book book = new Book(id, title, author, publish_year, page_count); books.add(book); } return books; } public boolean delete(Book book) throws SQLException { String sql = "DELETE FROM books WHERE id = ?"; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setInt(1, book.getId()); return stmt.executeUpdate() == 1; } } [/code] [b] hellocontroller [/b] [code] package com.example.konyvtarasztali; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import java.sql.SQLException; import java.util.Optional; public class HelloController { @FXML private TableView bookTable; @FXML private TableColumn titleCol; @FXML private TableColumn authorCol; @FXML private TableColumn publish_yearCol; @FXML private TableColumn page_countCol; private BookService bookService; public void initialize() { titleCol.setCellValueFactory(new PropertyValueFactory("title")); authorCol.setCellValueFactory(new PropertyValueFactory("author")); publish_yearCol.setCellValueFactory(new PropertyValueFactory("publish_year")); page_countCol.setCellValueFactory(new PropertyValueFactory("page_count")); try { bookService = new BookService(); refreshBooks(); } catch (SQLException e) { Platform.runLater(() -> { alert(Alert.AlertType.ERROR, "Nem sikerült kapcsolódni az adatbázishoz. Az alkalmazás leáll", e.getMessage()); Platform.exit(); }); } } private static Optional alert(Alert.AlertType alertType, String headerText) { return alert(alertType, headerText, ""); } private static Optional alert(Alert.AlertType alertType, String headerText, String contentText) { Alert alert = new Alert(alertType); alert.setHeaderText(headerText); alert.setContentText(contentText); return alert.showAndWait(); } private void refreshBooks() throws SQLException { bookTable.getItems().clear(); bookTable.getItems().addAll(bookService.getAll()); } @FXML public void deleteClick() { Book selected = bookTable.getSelectionModel().getSelectedItem(); if (selected == null) { alert(Alert.AlertType.WARNING, "Törléshez előbb válasszon ki könyvet"); return; } Optional selectedButton = alert(Alert.AlertType.CONFIRMATION, "Biztos szeretné törölni a kiválasztott könyvet?"); if (selectedButton.isPresent() && selectedButton.get().equals(ButtonType.OK)) { deleteBook(selected); } } private void deleteBook(Book book) { try { if (bookService.delete(book)) { alert(Alert.AlertType.INFORMATION, "Sikeres törlés"); } else { alert(Alert.AlertType.WARNING, "Sikertelen törlés", "A könyv már korábban törölve lett"); } refreshBooks(); } catch (SQLException e) { alert(Alert.AlertType.ERROR, "Hiba történt a törlés során", e.getMessage()); } } } [/code] [b] main [/b] [code] package com.example.konyvtarasztali; import java.util.Arrays; public class Main { public static void main(String[] args) { if (Arrays.asList(args).contains("--stat")) { Statisztika.main(args); } else { HelloApplication.main(args); } } } [/code] [b] Статистика [/b] [code] package com.example.konyvtarasztali; import java.sql.SQLException; import java.util.*; import java.util.stream.Collectors; public class Statisztika { private Statisztika() {} private static List books; public static void main(String[] args) { try { readBooksFromDatabase(); System.out.printf("500 oldalnál hosszabb könyvek száma: %d\n", countLongerThan500Pages()); System.out.printf("%s 1950-nél régebbi könyv\n", isOlderThan1950Present()? "Van" : "Nincs"); Book longest = getLongest(); System.out.printf("A leghosszabb könyv:\n" + "\tSzerző: %s\n" + "\tCím: %s\n" + "\tKiadás éve: %d\n" + "\tOldalszám: %d\n", longest.getAuthor(), longest.getTitle(), longest.getPublish_year(), longest.getPage_count()); System.out.printf("A legtöbb könyvvel rendelkező szerző: %s\n", getAuthorWithMostBooks()); String title = readFromConsole(); printAuthor(title); } catch (SQLException e) { System.err.println("Nem sikerült csatlakozni az adatbázishoz, az alkalmazás leáll!"); System.out.println(e.getMessage()); } } private static void printAuthorStream(String title) { Optional optionalKonyv = books.stream().filter(book -> book.getTitle().equals(title)).findFirst(); if (optionalKonyv.isPresent()) { System.out.printf("A megadott könyv szerzője %s\n", optionalKonyv.get().getAuthor()); } else { System.out.println("Nincs ilyen könyv"); } } private static void printAuthor(String title) { int ind = 0; while (ind < books.size() && !books.get(ind).getTitle().equals(title)) { ind++; } if (ind < books.size()) { System.out.printf("A megadott könyv szerzője %s\n", books.get(ind).getAuthor()); } else { System.out.println("Nincs ilyen könyv"); } } private static String readFromConsole() { Scanner sc = new Scanner(System.in); System.out.print("Adjon meg egy könyv címet: "); return sc.nextLine(); } private static String getAuthorWithMostBooksStream() { return books.stream() // Csoportosítás, a létrejött map kulcs-érték: szerző(string)-rekordszám(long) .collect(Collectors.groupingBy(Book::getAuthor, Collectors.counting())) .entrySet().stream() .max(Comparator.comparingLong(Map.Entry::getValue)) .get() .getKey(); } private static String getAuthorWithMostBooks() { Map authorBookCounts = new HashMap(); for (Book book: books) { authorBookCounts.putIfAbsent(book.getAuthor(), 0L); long count = authorBookCounts.get(book.getAuthor()); authorBookCounts.put(book.getAuthor(), count + 1); } String authorWithMostBooks = ""; long maxBookCount = 0; for (Map.Entry authorBookCount: authorBookCounts.entrySet()) { if (authorBookCount.getValue() > maxBookCount) { authorWithMostBooks = authorBookCount.getKey(); maxBookCount = authorBookCount.getValue(); } } return authorWithMostBooks; } private static Book getLongestStream() { return books.stream().max(Comparator.comparingInt(Book::getPage_count)).get(); } private static Book getLongest() { Book longest = books.get(0); for (int i = 1; i < books.size(); i++) { if (books.get(i).getPage_count() > longest.getPage_count()) { longest = books.get(i); } } return longest; } private static boolean isOlderThan1950PresentStream() { return books.stream().anyMatch(book -> book.getPublish_year() < 1950); } private static boolean isOlderThan1950Present() { int ind = 0; while (ind < books.size() && !(books.get(ind).getPublish_year() < 1950)) { ind++; } return ind < books.size(); } private static long countLongerThan500PagesWithStream() { return books.stream().filter(book -> book.getPage_count() > 500).count(); } private static long countLongerThan500Pages() { long count = 0; for (Book book: books) { if (book.getPage_count() > 500) { count++; } } return count; } private static void readBooksFromDatabase() throws SQLException { BookService db = new BookService(); books = db.getAll(); } } [/code] [b] hello-view [/b] < /code> , чтобы решить задачу, но я не могу ее получить, потому что я шик> Подробнее здесь: [url]https://stackoverflow.com/questions/79569630/connection-refused-html-backend-frondtend[/url]