我对JDBC非常陌生,我正在练习执行查询和语句。
try{
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
Statement st = conn.createStatement();
String queary = "SELECT COUNT(*) AS \"Number of suplliers\", city\r\n" +
"FROM supplier\r\n" +
"GROUP BY city\r\n" +
"ORDER BY city DESC\r\n";
//st.executeUpdate(queary);
ResultSet rs = st.executeQuery(queary);
while(rs.next()) {
System.out.println(rs.getString("supplierNum"));
System.out.println(rs.getString("city"));
space();
}
st.close();
conn.close();
}
我正在尝试使用SELECT COUNT(supplierNum) AS "Number of suplliers", cityFROM supplierGROUP BY city ORDER BY city DESC;
执行并打印结果
控制台刚刚终止,没有任何反应,没有错误消息,只是一个空白屏幕。
这是我要访问的表
CREATE TABLE supplier (
supplierNum CHAR(2) NOT NULL,
name CHAR(10) NOT NULL,
status TINYINT(4) NOT NULL,
city VARCHAR(10) NOT NULL,
PRIMARY KEY (supplierNum)
);
您将count列别名为"Number of suplliers"
,但是您的JDBC代码正在尝试查找supplierNum
。在各处使用一致的别名来解决此问题:
String query = "SELECT city, COUNT(*) AS supplierCnt " +
"FROM supplier " +
"GROUP BY city " +
"ORDER BY city DESC";
ResultSet rs = st.executeQuery(queary);
while (rs.next()) {
System.out.println(rs.getString("supplierCnt"));
System.out.println(rs.getString("city"));
space();
}