用jdbc连接数据库的社区管理并增删改查再用jdbc根据id查指定信息
时间: 2024-03-22 09:42:43 浏览: 20
好的,下面是用JDBC连接数据库的社区管理并增删改查的示例代码:
```java
import java.sql.*;
public class CommunityManager {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
public CommunityManager() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/community";
conn = DriverManager.getConnection(url, "root", "password");
} catch (Exception e) {
e.printStackTrace();
}
}
public void add(Community community) {
try {
String sql = "INSERT INTO community (name, description) VALUES (?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, community.getName());
pstmt.setString(2, community.getDescription());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void delete(int id) {
try {
String sql = "DELETE FROM community WHERE id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void update(int id, Community community) {
try {
String sql = "UPDATE community SET name=?, description=? WHERE id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, community.getName());
pstmt.setString(2, community.getDescription());
pstmt.setInt(3, id);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public Community getById(int id) {
Community community = null;
try {
String sql = "SELECT * FROM community WHERE id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
community = new Community(rs.getInt("id"), rs.getString("name"), rs.getString("description"));
}
} catch (Exception e) {
e.printStackTrace();
}
return community;
}
public void close() {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上面的代码中,我们使用JDBC连接到MySQL数据库,实现了社区管理的增删改查功能。其中,Community类表示社区实体,包含id、名称和描述等属性。CommunityManager类是管理社区的类,包含了增加、删除、更新和查询社区信息的方法。在getById方法中,我们通过传入id参数,来查询指定id的社区信息。
下面是根据id查找指定社区信息的示例代码:
```java
public static void main(String[] args) {
CommunityManager manager = new CommunityManager();
Community community = manager.getById(1);
if (community != null) {
System.out.println("社区名称:" + community.getName());
System.out.println("社区描述:" + community.getDescription());
} else {
System.out.println("查无此社区!");
}
manager.close();
}
```
在上面的代码中,我们实例化了CommunityManager类,并调用了它的getById方法来获取id为1的社区信息。如果查询成功,就会输出社区名称和描述,否则输出“查无此社区!”的提示信息。