使用DBC技术,把班级通讯录管理系统的数据保存在数据库中,实现学生通讯信息管理Java代码及其详细信息
时间: 2024-09-27 09:18:11 浏览: 32
VF.rar_VF数据库系统_Visual FoxPro系统_学生档案管理系统_智能档案_毕业设计
DBC(Database Connectivity)通常指数据库连接,用于在Java程序中操作数据库。为了实现班级通讯录管理系统,我们可以使用JDBC(Java Database Connectivity)API来完成数据存储和管理。以下是一个简单的示例,展示了如何创建表、插入数据以及查询学生信息:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class StudentManager {
private static final String DB_URL = "jdbc:mysql://localhost:3306/class_directory";
private static final String USER = "username";
private static final String PASS = "password";
// 连接到数据库
public static void connectToDB() throws Exception {
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
if (conn != null) {
System.out.println("Connected to the database");
} else {
throw new Exception("Failed to connect to the database");
}
}
// 插入学生信息
public static void insertStudentInfo(String studentId, String name, String email) {
String sqlInsert = "INSERT INTO students (id, name, email) VALUES (?, ?, ?)";
try (Connection conn = connectToDB();
PreparedStatement pstmt = conn.prepareStatement(sqlInsert)) {
pstmt.setString(1, studentId);
pstmt.setString(2, name);
pstmt.setString(3, email);
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
System.out.printf("Inserted student %s successfully%n", name);
} else {
System.err.println("Failed to insert student information");
}
} catch (Exception e) {
System.err.println("Error while inserting data: " + e.getMessage());
}
}
// 查询学生信息
public static void queryStudentInfo(String id) {
String sqlSelect = "SELECT * FROM students WHERE id = ?";
try (Connection conn = connectToDB();
PreparedStatement pstmt = conn.prepareStatement(sqlSelect)) {
pstmt.setString(1, id);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println("Found student with ID " + id + ": Name - " + name + ", Email - " + email);
} else {
System.out.println("No student found with ID: " + id);
}
} catch (Exception e) {
System.err.println("Error while querying data: " + e.getMessage());
}
}
public static void main(String[] args) {
// 示例用法
insertStudentInfo("101", "张三", "zhangsan@example.com");
queryStudentInfo("101");
}
}
```
在这个例子中,我们假设有一个名为`students`的表,包含`id`, `name`, 和 `email`字段。注意,你需要将`DB_URL`, `USER`, 和 `PASS`替换为你实际的数据库连接信息。
阅读全文