JDBC工具类

JDBC工具类

通过封装相关操作,创建JDBC相关的方法,如创建连接、关闭资源等,提升代码的可重用性。

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

public class JDBCUtil {
    private static final String DRIVER_NAME="com.mysql.cj.jdbc.Driver";
    private static  String url="";
    private static  String user="";
    private static  String psw="";
    static {
        try {
            Class.forName(DRIVER_NAME);
            Properties properties = new Properties();
            try {
                //FileInputStream fileInputStream = new FileInputStream("day24/src/db.properties");
                //properties.load(fileInputStream);
                properties.load(JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties"));
                user = properties.getProperty("user");
                psw = properties.getProperty("psw");
                url = properties.getProperty("url");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

    }
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,user,psw);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }
    public static void close(Connection connection){
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public static void close(Statement statement){
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public static void close(ResultSet resultSet){
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

posted @   zeliCouer  阅读(225)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示