zoukankan      html  css  js  c++  java
  • JDBC 04: 创建JDBCUtils并重构之前的代码

    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);
            }
        }
  • 相关阅读:
    贪心[2019.5.25]
    顺序统计算法[2019.5.25]
    polya/burnside 学习
    虚拟机上装uoj
    一些常用的数据结构维护手法
    发一个数据生成器
    圆方树学习
    四校联考 推冰块
    Codeforces Training S03E01泛做
    HAOI2015 泛做
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13539484.html
Copyright © 2011-2022 走看看