JDBCUtils.java

2022/3/30 9:19:27

本文主要是介绍JDBCUtils.java,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package com.life.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {

    public static Connection getConnection() throws Exception {
        // 1.读取配置文件中的4个基本信息
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");

        Properties pros = new Properties();
        pros.load(is);

        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driverClass = pros.getProperty("driverClass");

        // 2.加载注册驱动
        Class.forName(driverClass);

        // 3.获取连接
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }
    
    public static void closeResource(Connection conn){
        closeResource(conn,null,null);
    }
    
    public static void closeResource(Statement ps){
        closeResource(null,ps,null);
    }

    public static void closeResource(Connection conn,Statement ps){
        closeResource(conn,ps,null);
    }
    
    public static void closeResource(Statement ps, ResultSet rs)){
        closeResource(null,ps,rs);
    }

    public static void closeResource(Connection conn,Statement ps,ResultSet rs){
        try {
            if(ps != null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 



这篇关于JDBCUtils.java的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程