JAVA根据数据库查询学生成绩
时间: 2023-10-24 15:08:45 浏览: 46
好的,您可以参考以下代码实现JAVA根据数据库查询学生成绩的功能:
```java
import java.sql.*;
public class QueryScores {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 创建数据库连接
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
// 3. 创建Statement对象
stmt = conn.createStatement();
// 4. 执行SQL语句
String sql = "SELECT * FROM student_score";
rs = stmt.executeQuery(sql);
// 5. 处理查询结果
while (rs.next()) {
String name = rs.getString("name");
int score = rs.getInt("score");
System.out.println("姓名:" + name + ",成绩:" + score);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6. 释放资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
其中,需要替换的部分如下:
- 数据库连接信息(url、username、password)
- SQL查询语句(sql)
- 查询结果的处理方式(while循环内部的代码)
请根据实际情况进行替换。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)