2:Jdbc工具类

Posted 梁云亮

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2:Jdbc工具类相关的知识,希望对你有一定的参考价值。

版本一:最基本的Jdbc工具类

public class JdbcUtil {

    private static String url = "jdbc:mysql://localhost:3306/db_data_show_5?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false";
    private static String password = "root";
    private static String user = "root";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     *
     * @param rs
     * @param stmt
     * @param conn
     */
    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        final Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

}

版本二:抽取连接信息后的工具类

  • 第一步:在resources目录下创建mysql.properties文件
url=jdbc:mysql://localhost:3306/db_data_show_5?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false
password=root
user=root
  • 第二步:使用配置文件的工具类
public class JdbcUtil {

    private static String url ;
    private static String password;
    private static String user;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            final Properties properties = new Properties();
            //getResourceAsStream:读取文件,在JavaSE和javaWeb中都可以用,注意路径问题
            final InputStream is = JdbcUtil.class.getResourceAsStream("/mysql.properties");
            properties.load(is);
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            is.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        final Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }
    
    /**
     * 释放资源
     *
     * @param rs
     * @param stmt
     * @param conn
     */
    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws SQLException {
        final Connection conn = getConnection();
        System.out.println(conn);
    }

}

版本三:添加Druid数据库连接支持

  • 添加Druid依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.17</version>
</dependency>
  • 修改mysql.properties
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_data_show_5?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false
username=root
password=root

# 初始化时创建的连接的个数
initialSize=10
# 处于活跃状态的连接的个数
maxActive=20
# 连接最多等待时长
maxWait=6000
  • 修改JdbcUtil:
public class JdbcUtil {

    private static DataSource dataSource;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            final Properties properties = new Properties();
            //getResourceAsStream:读取文件,在JavaSE和javaWeb中都可以用,注意路径问题
            final InputStream is = JdbcUtil.class.getResourceAsStream("/mysql.properties");
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
           is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        final Connection conn =dataSource.getConnection();
        return conn;
    }

    /**
     * 释放资源
     *
     * @param rs
     * @param stmt
     * @param conn
     */
    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws SQLException {
        final Connection conn = getConnection();
        System.out.println(conn);
    }

}

版本四:添加LocalThread以支持并发

public class JdbcUtil {

    private static DataSource dataSource;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            final Properties properties = new Properties();

            //getResourceAsStream:读取文件,在JavaSE和javaWeb中都可以用,注意路径问题
            final InputStream is = JdbcUtil.class.getResourceAsStream("/mysql.properties");
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
            is.close();
        } catch (Exception e) {
            throw new RuntimeException("读取配置文件错误");
        }

    }

    /**
     * 获取连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() {
        Connection conn = threadLocal.get();
        try {
            if (conn == null || conn.isClosed()) {
                conn = dataSource.getConnection();
                threadLocal.set(conn);
            }
        } catch (SQLException e) {
            throw new RuntimeException("获取连接失败!");
        }
        return conn;
    }

    /**
     * 释放资源
     *
     * @param rs
     * @param stmt
     * @param conn
     */
    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) throws SQLException {
        final Connection conn = getConnection();
        System.out.println(conn);
    }

}

以上是关于2:Jdbc工具类的主要内容,如果未能解决你的问题,请参考以下文章

elasticsearch代码片段,及工具类SearchEsUtil.java

JavaWeb - JDBC各个类详解工具类解决sql注入

JavaWeb - JDBC各个类详解工具类解决sql注入

JDBC工具类连接数据库,模仿登录

2:Jdbc工具类

jdbc工具类2..0