用java和MySQL实现访客管理系统的黑名单增删改查功能的代码,并且这个代码里包含了异常处理。
时间: 2023-06-24 09:05:51 浏览: 94
Java语言实现对MySql数据库中数据的增删改查操作的代码
以下是一个简单的访客管理系统的黑名单增删改查功能的Java代码,其中包括异常处理:
```java
import java.sql.*;
public class Blacklist {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/guestbook";
private static final String USER = "root";
private static final String PASSWORD = "password";
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
public void addGuestToBlacklist(int guestId) {
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASSWORD);
String sql = "INSERT INTO blacklist(guest_id) VALUES(?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, guestId);
preparedStatement.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
closeConnection();
}
}
public void removeGuestFromBlacklist(int guestId) {
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASSWORD);
String sql = "DELETE FROM blacklist WHERE guest_id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, guestId);
preparedStatement.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
closeConnection();
}
}
public void updateGuestInBlacklist(int guestId, int newGuestId) {
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASSWORD);
String sql = "UPDATE blacklist SET guest_id=? WHERE guest_id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, newGuestId);
preparedStatement.setInt(2, guestId);
preparedStatement.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
closeConnection();
}
}
public boolean isGuestInBlacklist(int guestId) {
boolean isInBlacklist = false;
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASSWORD);
String sql = "SELECT * FROM blacklist WHERE guest_id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, guestId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
isInBlacklist = true;
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
closeConnection();
}
return isInBlacklist;
}
private void closeConnection() {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们使用了Java的JDBC API来连接MySQL数据库,并使用预处理语句来执行增删改查操作。在每个方法中,我们都使用了try-catch块来捕获可能发生的异常,并在最后使用finally块来关闭连接、语句和结果集。这有助于保持代码的可读性和可维护性。
值得注意的是,上面的代码只是一个示例,可能需要根据具体的需求进行修改和优化。例如,我们可能需要添加更多的方法来处理不同的业务逻辑,或使用连接池来提高性能。
阅读全文