jdbc数据库连接工具类

package uitl;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {

    private static String url ="";
    private static String user ="";
    private static String password ="";
    private static String driveClass="";
    /**
     * 注册驱动程序的静态代码块
     */
    static {
        try {

            Properties properties=new Properties();


            InputStream resourceAsStream = JDBCUtil.class.getResourceAsStream("/db.properties");
            properties.load(resourceAsStream);

            url = properties.getProperty("url");
            user= properties.getProperty("user");
            password=properties.getProperty("password");
            driveClass=properties.getProperty("DriveClass");

            Class.forName(driveClass);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("驱动注册失败!");
        }
    }

    /**
     * 获取链接的方法
     */

    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return connection;
    }
    /**
     * 关闭链接的方法
     */

    public static void close(Connection connection, Statement statement){
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。