-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBookService.java
More file actions
55 lines (49 loc) · 1.9 KB
/
Copy pathBookService.java
File metadata and controls
55 lines (49 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package services;
import database.Database
import models.Book;
public class BookService {
public static void addBook(String title, String author) {
String sql = "INSERT INTO books (title, author, available) VALUES (?, ?, 1)";
try (Connection conn = Database.connect();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(2, author);
System.out.println("Book added successfully.");
} catch (SQLException e) {
System.out.println("Error adding book: " + e.getMessage());
}
}
public static List<Book> getAllBooks() {
List<Book> books = new ArrayList<>();
String sql = "SELECT * FROM books";
try (Connection conn = Database.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
books.add(new Book(
rs.getInt("id"),
rs.getString("title"),
rs.getString("author"),
rs.getBoolean("available")
));
}
} catch (SQLException e) {
System.out.println("Error fetching books: " + e.getMessage());
}
return books;
}
public static void deleteBook(int bookId) {
String sql = "DELETE FROM books WHERE id = ?";
try (Connection conn = Database.connect();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, bookId);
int rowsAffected = stmt.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Book deleted successfully.");
} else {
System.out.println("Book ID not found.");
}
} catch (SQLException e) {
System.out.println("Error deleting book: " + e.getMessage());
}
}
}