1. 创建JDBCUtils
package com.Jasper2003.jdbc01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCUtils { private static final String connectionURL = "jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF8&useSSL=false"; private static final String username = "root"; private static final String password = "root"; public static Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection(connectionURL,username,password); }catch(Exception e) { e.printStackTrace(); } return null; } public static void close(ResultSet rs, Statement stmt, Connection con) { try { if(rs!=null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(stmt!=null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(con!=null) con.close(); } catch (SQLException e) { e.printStackTrace(); } } }
2. 重构selectAll()
public static void selectAll() { Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = JDBCUtils.getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery("select * from user"); while(rs.next()) { System.out.println(rs.getInt("id")+","+rs.getString("username")+","+rs.getString("password")); } } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.close(rs, stmt, con); } }