利用jdbc写出一个图书管理表方便增删改查
时间: 2024-12-19 10:15:44 浏览: 4
使用Java JDBC(Java数据库连接)操作图书管理表,我们通常会创建四个基本的CRUD(Create, Read, Update, Delete)操作的示例方法。这里是一个简单的例子,假设我们的表名为`LibraryBooks`,有`book_id`, `title`, `author`, `publisher`, `isbn`, `stock_quantity`和`borrow_status`字段。
```java
import java.sql.*;
public class LibraryManagement {
private Connection connection; // 数据库连接
public void connectToDatabase(String url, String username, String password) throws SQLException {
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
System.err.println("Error connecting to the database: " + e.getMessage());
}
}
// 创建图书
public boolean addBook(Book book) throws SQLException {
String sql = "INSERT INTO LibraryBooks (title, author, publisher, isbn, stock_quantity, borrow_status)"
+ "VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, book.getTitle());
pstmt.setString(2, book.getAuthor());
pstmt.setString(3, book.getPublisher());
pstmt.setString(4, book.getIsbn());
pstmt.setInt(5, book.getStockQuantity());
pstmt.setString(6, book.getBorrowStatus());
return pstmt.executeUpdate() > 0;
}
// 查询图书
public ResultSet getBooksByTitle(String title) throws SQLException {
String sql = "SELECT * FROM LibraryBooks WHERE title LIKE ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, "%" + title + "%");
return pstmt.executeQuery();
}
// 更新图书状态
public int updateBookStatus(int bookId, String newStatus) throws SQLException {
String sql = "UPDATE LibraryBooks SET borrow_status = ? WHERE book_id = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, newStatus);
pstmt.setInt(2, bookId);
return pstmt.executeUpdate();
}
// 删除图书
public boolean deleteBook(int bookId) throws SQLException {
String sql = "DELETE FROM LibraryBooks WHERE book_id = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, bookId);
return pstmt.executeUpdate() > 0;
}
}
```
每个方法都对应了相应的数据库操作,并需要关闭PreparedStatement和Connection以释放资源。注意在实际应用中,错误处理和日志记录是非常重要的部分。
阅读全文