水王
连接数据库一次查找:
package 水王; import java.sql.*; public class ShuiWang { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/two"; static final String USER = "root"; static final String PASS = "mm123456"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName("com.mysql.jdbc.Driver"); // 打开链接 conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 stmt = conn.createStatement(); String sql1; sql1 = "SELECT * ,count(name) as total from shuiwang GROUP BY name order by total desc limit 1"; ResultSet rs1 = stmt.executeQuery(sql1); // 展开结果集数据库 while(rs1.next()){ // 通过字段检索 String name = rs1.getString("name"); int total=rs1.getInt("total"); // 输出数据 System.out.println("水王的名字为:" + name); System.out.println("水王出现的次数:" +total); System.out.print("\n"); } // 完成后关闭 rs1.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(); } } } }