合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
## 实例 ~~~ public class JDBCUtils { private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; private static final String URL = "jdbc:mysql://192.168.10.10:3306/jdbc"; private static final String USERNAME = "homestead"; private static final String PASSWORD = "secret"; static { //驱动只需要加载一次就可以了 try { Class.forName(DRIVER_NAME); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException(); } } public static Connection getConnection() throws ClassNotFoundException, SQLException { return DriverManager.getConnection(URL, USERNAME, PASSWORD); } public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ~~~ ~~~ public class main { public static void main(String[] args) { Connection conn = null; Statement statement = null; ResultSet resultset = null; try { conn = JDBCUtils.getConnection(); statement = conn.createStatement(); resultset = statement.executeQuery("select * from category"); while (resultset.next()) { Object cid = resultset.getObject("cid"); Object cname = resultset.getObject("cname"); System.out.println(cid + ":" + cname); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { JDBCUtils.closeAll(conn, statement, resultset); } } } ~~~