基于Java Swing + MySQL的图书管理系统
以下是一个简化的Java Swing + MySQL图书管理系统的代码示例,仅包含数据库连接和查询操作的部分。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BookManagementSystem {
private Connection connect = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public BookManagementSystem() {
// 初始化数据库连接
String url = "jdbc:mysql://localhost:3306/book_database";
String username = "root";
String password = "password";
try {
// 加载MySQL JDBC驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立连接
connect = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet searchBooks(String bookTitle) {
String query = "SELECT * FROM books WHERE title LIKE ?";
try {
// 准备查询
preparedStatement = connect.prepareStatement(query);
// 设置参数
preparedStatement.setString(1, "%" + bookTitle + "%");
// 执行查询
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
public void closeConnections() {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connect != null) {
connect.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
BookManagementSystem bookSystem = new BookManagementSystem();
ResultSet books = bookSystem.searchBooks("Java");
try {
while (books.next()) {
System.out.println(books.getString("title"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
bookSystem.closeConn
评论已关闭