/* Test3.java 查看1年级1班共有多少学生 */ public static void main(String[] args) { try (Connection connection = DBUtil.getConnection();){ Statement statement = connection.createStatement(); String sql = "SELECT c.name,COUNT(s.id) FROM class c,student s WHERE s.class_id=c.id,AND c.name='1年级1班'"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ String cname = resultSet.getString("c.name"); int count = resultSet.getInt("COUNT(s.id)"); System.out.println(""+cname+","+count); } } catch (SQLException throwables) { throwables.printStackTrace(); } }改正该代码
时间: 2024-02-14 14:15:49 浏览: 221
代码存在两个问题:
1. SQL语句中逗号的位置不正确,应该是WHERE s.class_id=c.id AND c.name='1年级1班'。
2. 在输出结果时,应该将count值转换为字符串类型,否则会被当成加法运算。
修改后的代码如下:
```
/* Test3.java 查看1年级1班共有多少学生 */
public static void main(String[] args) {
try (Connection connection = DBUtil.getConnection();) {
Statement statement = connection.createStatement();
String sql = "SELECT c.name,COUNT(s.id) FROM class c,student s WHERE s.class_id=c.id AND c.name='1年级1班'";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String cname = resultSet.getString("c.name");
int count = resultSet.getInt("COUNT(s.id)");
System.out.println("" + cname + "," + String.valueOf(count));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
```
阅读全文