简易版封装数据库链接工具类

 首先在src下面创建一个文档,文档的内容是连接时需要用到的各种参数

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/java2304?useSSL=false
user=root
password=123456

具体封装的内容

/**
 * 封装jdbc连接数据和关闭数据库
 */
public class JdbcUtil {
    private  static String url=null;    //设置url属性
    private  static String user=null;   //设置user熟悉
    private  static String password=null; //设置password熟悉
    static {                        //静态代码块这里的静态代码块的作用调用这个封装时,先获取url user password的参数,为下面的加载做准备
        try {
            Properties properties = new Properties();   //实例化Properties类
            properties.load(new FileInputStream("src/db.properties"));  //用IO流读取配置信息的参数
            String driver = properties.getProperty("driver");  //获取加载驱动的参数
             url = properties.getProperty("url");     //获取url参数
             user=properties.getProperty("user");    //获取user参数
             password =properties.getProperty("password");   //获取password参数
             Class.forName(driver);                 //加载驱动
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public  static Connection getConnection(){   //创建连接方法
        Connection connection=null;    //创建connection
        try {
            connection  = DriverManager.getConnection(url,user,password);//建立连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;  //返回连接
    }
    public static void close(Connection connection){
        try {
            connection.close();  //关闭connection连接对象
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public  static   void  close( Statement statement, Connection connection){
        try {
            statement.close();   //关闭statement搬运工
            connection.close();   //关闭connection连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public  static   void  close(ResultSet resultSet,Statement statement,Connection connection){
        try {
            resultSet.close();   //关闭结果集
            statement.close();   //关闭statement搬运工
            connection.close();  //关闭connection连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值