錯誤代碼
ResultSet rst = stt.executeQuery("select count(*) from t_students");
out.print(rst.getString("")); // ❌ 空字串無效
正確方式
- 別名 + getInt/getLong (推薦):
ResultSet rst = stt.executeQuery("select count(*) as cnt from t_students");
if (rst.next()) {
int total = rst.getInt("cnt"); // 或 getLong
out.print(total);
}
- 索引存取:
if (rst.next()) out.print(rst.getInt(1));
- getString 索引:
out.print(rst.getString(1));
完整範例
<%
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "pass");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT COUNT(*) AS total FROM t_students");
if (rs.next()) {
out.println("學生總數: " + rs.getInt("total"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (conn != null) conn.close(); } catch (Exception ignored) {}
}
%>
關鍵點
- 聚合查詢**必須給別名**或用索引 1 取值。
- 永遠用
if (rs.next()) 而非 while,因 COUNT 只返回一行。
- 資源在 finally 關閉,防洩漏。