java实现mysql学生成绩
时间: 2023-12-19 19:31:35 浏览: 18
以下是使用Java连接MySQL数据库实现学生成绩管理的示例代码:
```java
import java.sql.*;
public class StudentScoreManagement {
// JDBC驱动器名称和数据库URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/student";
// 数据库凭据
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册JDBC驱动器
Class.forName(JDBC_DRIVER);
// 打开一个连接
System.out.println("连接到数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, score FROM student_score";
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
int score = rs.getInt("score");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 姓名: " + name);
System.out.println(", 分数: " + score);
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// 处理JDBC错误
se.printStackTrace();
} catch (Exception e) {
// 处理Class.forName错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // 什么都不做
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
```
上述代码实现了连接到MySQL数据库,查询学生的成绩信息并输出。你可以根据需要修改代码以实现增删改查等功能。