标签:localhost final dbutil oca rgs manage man 结果 ring
public class DBUtils { // 不变的东西 private static String driverclass = "com.mysql.cj.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/test"; private static String user = "root"; private static String password = "123456"; // static语句块,该类被加载的时候会被执行且只执行一次,驱动注册 static { try { Class.forName(driverclass); } catch (ClassNotFoundException e) { e.printStackTrace(); } } // 建立连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } // 释放连接 public static void close(ResultSet resultSet, Statement statement, Connection connection) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
public class JDBC_01 { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { // // 1.注册驱动。现在这一句不需要了,DBUtils类被加载的时候会执行static块 // Class.forName("com.mysql.cj.jdbc.Driver"); // 2.创建连接 connection = DBUtils.getConnection(); // 3.创建执行SQL语句的对象 statement = connection.createStatement(); // 4.执行SQL语句并返回结果集 resultSet = statement.executeQuery("select * from user;"); // 5.遍历 while (resultSet.next()) { System.out.print(resultSet.getObject(1) + " "); System.out.print(resultSet.getObject(2) + " "); System.out.print(resultSet.getObject(3) + " "); System.out.print(resultSet.getObject(4) + " "); System.out.println(resultSet.getObject(5) + " "); } } catch (Exception e) { // TODO: handle exception } finally { DBUtils.close(resultSet, statement, connection); } } }
标签:localhost final dbutil oca rgs manage man 结果 ring
原文地址:https://www.cnblogs.com/pilgrimL/p/10200568.html