用java和MySQL实现访客管理系统的黑名单功能代码,要求黑名单功能里有增删改查功能
时间: 2024-05-16 17:15:32 浏览: 120
这里给出一个简单的访客管理系统的黑名单功能代码,使用Java和MySQL实现。其中,访客表的结构为id、name、phone、email、is_blacklist,is_blacklist字段表示是否在黑名单中(0表示不在,1表示在)。
增加黑名单:
```java
public void addToBlacklist(int visitorId) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
String sql = "UPDATE visitors SET is_blacklist = 1 WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, visitorId);
ps.executeUpdate();
} finally {
close(conn, ps, null);
}
}
```
移出黑名单:
```java
public void removeFromBlacklist(int visitorId) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
String sql = "UPDATE visitors SET is_blacklist = 0 WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, visitorId);
ps.executeUpdate();
} finally {
close(conn, ps, null);
}
}
```
修改黑名单状态:
```java
public void updateBlacklistStatus(int visitorId, int status) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getConnection();
String sql = "UPDATE visitors SET is_blacklist = ? WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, status);
ps.setInt(2, visitorId);
ps.executeUpdate();
} finally {
close(conn, ps, null);
}
}
```
查询黑名单列表:
```java
public List<Visitor> getBlacklist() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Visitor> list = new ArrayList<>();
try {
conn = getConnection();
String sql = "SELECT * FROM visitors WHERE is_blacklist = 1";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Visitor visitor = new Visitor();
visitor.setId(rs.getInt("id"));
visitor.setName(rs.getString("name"));
visitor.setPhone(rs.getString("phone"));
visitor.setEmail(rs.getString("email"));
visitor.setIsBlacklist(rs.getInt("is_blacklist"));
list.add(visitor);
}
} finally {
close(conn, ps, rs);
}
return list;
}
```
其中,getConnection()和close()方法为获取数据库连接和关闭资源的通用方法,这里不再赘述。
阅读全文