JDBC_DBUtils

  • 把建立连接和释放连接封装到工具类中,代码如下:
  • 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);
            }
        }
    }

     

posted @ 2018-12-30 20:22  PilgrimL  阅读(147)  评论(0编辑  收藏  举报