工具类

来源:互联网 发布:在职研究生网络教育 编辑:程序博客网 时间:2024/05/19 02:43
package cn.itcast.jdbc;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import cn.itcast.jdbc.dataSource.MyDataSource;public final class JdbcUtils {    private static MyDataSource myDataSource = null;    private JdbcUtils() {    }    static {        try {            Class.forName("com.mysql.jdbc.Driver");            myDataSource = new MyDataSource();        } catch (Exception e) {            throw new ExceptionInInitializerError(e);        }    }    public static Connection getConnection() throws SQLException {        // return DriverManager.getConnection(url, user, password); //原工具类:创建连接        return myDataSource.getConnection(); // 取连接    }    public static void free(ResultSet rs, Statement st, Connection conn) {        try {            if (rs != null)                rs.close();        } catch (SQLException e) {            e.printStackTrace();        } finally {            try {                if (st != null)                    st.close();            } catch (SQLException e) {                e.printStackTrace();            } finally {                try {                    if (conn != null)                        // conn.close(); //原工具类:关闭连接                        myDataSource.free(conn); // 释放连接                } catch (Exception e) {                    e.printStackTrace();                }            }        }    }}
0 0
原创粉丝点击