java语言 创建一学生数据库School,创建一表studb,包含字段:学号、姓名、性别、专业、入学年份。编写程序对studb表进行学生信息的增、删、改、查操作。
时间: 2023-09-19 10:08:19 浏览: 166
好的,我可以为您提供Java语言的代码实现。不过在开始之前,您需要先安装一个Java开发环境(JDK)并配置好环境变量。以下是代码实现:
```java
import java.sql.*;
public class School {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public School() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "password");
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
public void addStudent(String id, String name, String sex, String major, String year) {
try {
String sql = "INSERT INTO studb(id, name, sex, major, year) VALUES('" + id + "', '" + name + "', '" + sex + "', '" + major + "', '" + year + "')";
stmt.executeUpdate(sql);
System.out.println("学生信息添加成功!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
public void deleteStudent(String id) {
try {
String sql = "DELETE FROM studb WHERE id='" + id + "'";
stmt.executeUpdate(sql);
System.out.println("学生信息删除成功!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
public void updateStudent(String id, String name, String sex, String major, String year) {
try {
String sql = "UPDATE studb SET name='" + name + "', sex='" + sex + "', major='" + major + "', year='" + year + "' WHERE id='" + id + "'";
stmt.executeUpdate(sql);
System.out.println("学生信息更新成功!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
public void searchStudent(String id) {
try {
String sql = "SELECT * FROM studb WHERE id='" + id + "'";
rs = stmt.executeQuery(sql);
if (rs.next()) {
String name = rs.getString("name");
String sex = rs.getString("sex");
String major = rs.getString("major");
String year = rs.getString("year");
System.out.println("学号:" + id + "\t姓名:" + name + "\t性别:" + sex + "\t专业:" + major + "\t入学年份:" + year);
} else {
System.out.println("没有找到该学生的信息!");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
School school = new School();
// 添加学生信息
school.addStudent("001", "张三", "男", "计算机科学", "2019");
school.addStudent("002", "李四", "女", "软件工程", "2018");
school.addStudent("003", "王五", "男", "信息安全", "2017");
// 查找学生信息
school.searchStudent("001");
// 更新学生信息
school.updateStudent("002", "王丽", "女", "软件工程", "2017");
// 删除学生信息
school.deleteStudent("003");
}
}
```
这段代码实现了对学生信息的增、删、改、查操作。其中,`addStudent`方法用于添加学生信息,`deleteStudent`方法用于删除学生信息,`updateStudent`方法用于更新学生信息,`searchStudent`方法用于查找学生信息。在`main`方法中,我们通过调用这些方法来操作学生信息。需要注意的是,代码中的数据库连接信息需要根据您的实际情况进行修改。
阅读全文