Java聊天项目在DBUtil类中添加删除好友的代码;
时间: 2024-01-24 22:17:36 浏览: 79
在DBUtil类中添加和删除好友的代码如下:
```
// 添加好友
public static void addFriend(String username, String friendName) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String sql = "INSERT INTO friends (username, friendname) VALUES (?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, friendName);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(conn, pstmt, null);
}
}
// 删除好友
public static void deleteFriend(String username, String friendName) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String sql = "DELETE FROM friends WHERE username = ? AND friendname = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, friendName);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(conn, pstmt, null);
}
}
```
其中,`addFriend`方法将好友关系插入到数据库中的`friends`表中,`deleteFriend`方法将好友关系从数据库中删除。这里假设`friends`表的结构为:
```
CREATE TABLE friends (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
friendname VARCHAR(50) NOT NULL
);
```
阅读全文