用java写一个学生成绩管理系统的代码,能够进行增删改查的操作并与数据库连接
时间: 2023-04-03 15:05:11 浏览: 110
你好,以下是Java写一个学生成绩管理系统的代码,能够进行增删改查的操作并与数据库连接的示例代码:
import java.sql.*;
import java.util.Scanner;
public class StudentGradeManagementSystem {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/student_grade_management_system";
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS student " +
"(id INT NOT NULL AUTO_INCREMENT, " +
" name VARCHAR(255), " +
" age INT, " +
" gender VARCHAR(255), " +
" grade INT, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请选择操作:1.添加学生信息 2.删除学生信息 3.修改学生信息 4.查询学生信息 5.退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("请输入学生姓名:");
String name = scanner.next();
System.out.println("请输入学生年龄:");
int age = scanner.nextInt();
System.out.println("请输入学生性别:");
String gender = scanner.next();
System.out.println("请输入学生成绩:");
int grade = scanner.nextInt();
sql = "INSERT INTO student (name, age, gender, grade) VALUES ('" + name + "', " + age + ", '" + gender + "', " + grade + ")";
stmt.executeUpdate(sql);
System.out.println("添加成功!");
break;
case 2:
System.out.println("请输入要删除的学生姓名:");
name = scanner.next();
sql = "DELETE FROM student WHERE name='" + name + "'";
stmt.executeUpdate(sql);
System.out.println("删除成功!");
break;
case 3:
System.out.println("请输入要修改的学生姓名:");
name = scanner.next();
System.out.println("请输入修改后的学生年龄:");
age = scanner.nextInt();
System.out.println("请输入修改后的学生性别:");
gender = scanner.next();
System.out.println("请输入修改后的学生成绩:");
grade = scanner.nextInt();
sql = "UPDATE student SET age=" + age + ", gender='" + gender + "', grade=" + grade + " WHERE name='" + name + "'";
stmt.executeUpdate(sql);
System.out.println("修改成功!");
break;
case 4:
System.out.println("请输入要查询的学生姓名:");
name = scanner.next();
sql = "SELECT * FROM student WHERE name='" + name + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
age = rs.getInt("age");
gender = rs.getString("gender");
grade = rs.getInt("grade");
System.out.println("id:" + id + ",姓名:" + name + ",年龄:" + age + ",性别:" + gender + ",成绩:" + grade);
}
rs.close();
break;
case 5:
scanner.close();
stmt.close();
conn.close();
System.out.println("退出成功!");
System.exit(0);
default:
System.out.println("输入有误,请重新输入!");
break;
}
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
阅读全文