使用Derby数据库或者其它数据库,在数据库中,设计一张表,包括学号、姓名、年龄、班级等信息。使用Java编程,连接该数据库,写入、读出、修改、查询学生信息。
时间: 2024-04-08 21:35:29 浏览: 40
好的,我可以帮你回答这个问题。首先,你需要在数据库中创建一张表来存储学生信息。你可以使用以下的SQL语句在Derby数据库中创建这个表:
```sql
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
class VARCHAR(50)
);
```
接下来,你可以使用Java编程语言来连接数据库并进行操作。首先,你需要下载并安装Derby数据库驱动程序(Derby提供了一个名为"derbyclient.jar"的JDBC驱动)。然后,你可以使用以下的Java代码来连接数据库、写入、读出、修改和查询学生信息:
```java
import java.sql.*;
public class StudentDatabase {
public static void main(String[] args) {
try {
// 连接到数据库
Connection connection = DriverManager.getConnection("jdbc:derby://localhost:1527/myDB");
// 写入学生信息
insertStudent(connection, 1, "John", 20, "Class A");
// 读出学生信息
Student student = getStudent(connection, 1);
System.out.println("Student: " + student.getId() + ", " + student.getName() + ", " + student.getAge() + ", " + student.getClass());
// 修改学生信息
updateStudent(connection, 1, "John Doe");
// 查询学生信息
student = getStudent(connection, 1);
System.out.println("Student: " + student.getId() + ", " + student.getName() + ", " + student.getAge() + ", " + student.getClass());
// 关闭数据库连接
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 写入学生信息
public static void insertStudent(Connection connection, int id, String name, int age, String class) throws SQLException {
PreparedStatement statement = connection.prepareStatement("INSERT INTO students VALUES (?, ?, ?, ?)");
statement.setInt(1, id);
statement.setString(2, name);
statement.setInt(3, age);
statement.setString(4, class);
statement.executeUpdate();
}
// 读出学生信息
public static Student getStudent(Connection connection, int id) throws SQLException {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM students WHERE id = ?");
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
int studentId = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String class = resultSet.getString("class");
return new Student(studentId, name, age, class);
}
return null;
}
// 修改学生信息
public static void updateStudent(Connection connection, int id, String name) throws SQLException {
PreparedStatement statement = connection.prepareStatement("UPDATE students SET name = ? WHERE id = ?");
statement.setString(1, name);
statement.setInt(2, id);
statement.executeUpdate();
}
// 学生类
public static class Student {
private int id;
private String name;
private int age;
private String class;
public Student(int id, String name, int age, String class) {
this.id = id;
this.name = name;
this.age = age;
this.class = class;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getClass() {
return class;
}
}
}
```
请确保你已经将Derby数据库驱动程序的JAR文件添加到你的Java项目中。运行上述代码后,你将能够连接数据库,并进行写入、读出、修改和查询学生信息的操作。
阅读全文