Writing of Druid database connection pool tools

Packaging tools

In order to reduce the workload of the code, JDBC registration, obtaining connections, and releasing connections are encapsulated into a tool class; the
specific code is as follows:

public class JDBCUtils {
    //定义成员变量
    private static DataSource ds;
    static{
        try {
            //加载配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    //释放资源
    public static void close(Statement stmt,Connection conn){
        if(stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(ResultSet rs, Statement stmt, Connection conn){
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //获取连接池方法
    public  static DataSource getDataSource(){
        return ds;
    }
} 	

Call tool class

Specific examples of calling tool classes are as follows:

public class DruidDemo2 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            //获取连接
            conn = JDBCUtils.getConnection();
            //定义sql
            String sql = "insert into account values(null,?,?)";
            //获取pstmt对象
            pstmt = conn.prepareStatement(sql);
            //给?赋值
            pstmt.setString(1,"王五");
            pstmt.setDouble(2,3000);
            //执行sql
            int count = pstmt.executeUpdate();
            System.out.println(count);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //释放资源
            JDBCUtils.close(pstmt,conn);
        }
    }
}
Published 28 original articles · praised 0 · visits 722

Guess you like

Origin blog.csdn.net/William_GJIN/article/details/104706351