基于JDBC实现学生管理系统创建一个名为student的数据库表,编写JAVA程序实现增删改查
时间: 2024-12-25 21:28:57 浏览: 5
创建名为`student`的数据库表通常包含学生的姓名(name)、年龄(age)、性别(sex)等字段,可以使用以下SQL语句示例:
```sql
CREATE TABLE student (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age INT,
sex CHAR(1),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
这个表定义了一个自增ID作为主键,其他字段包括字符串类型的姓名、整型的年龄、单字符的性别以及默认设置的时间戳。
为了在Java中使用JDBC实现增删改查操作,你可以按照以下步骤编写代码:
**添加(Insert)**:
```java
String sqlInsert = "INSERT INTO student (name, age, sex) VALUES (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sqlInsert)) {
pstmt.setString(1, "张三");
pstmt.setInt(2, 20);
pstmt.setString(3, "M");
pstmt.executeUpdate();
}
```
**删除(Delete)**:
```java
String sqlDelete = "DELETE FROM student WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sqlDelete)) {
pstmt.setInt(1, 1); // 假设我们要删除id为1的学生
pstmt.executeUpdate();
}
```
**修改(Update)**:
```java
String sqlUpdate = "UPDATE student SET age = ?, sex = ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sqlUpdate)) {
pstmt.setInt(1, 21);
pstmt.setString(2, "F");
pstmt.setInt(3, 2);
pstmt.executeUpdate();
}
```
**查询(Read)**:
```java
String sqlSelect = "SELECT * FROM student WHERE name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sqlSelect)) {
pstmt.setString(1, "张三");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
}
```
记得在每个操作后检查执行结果(例如,executeUpdate()返回受影响的行数),以确保操作成功。
阅读全文