Java连接数据的工具类

首先

 连接数据库的方法有很多种,这里选择一种我喜欢的方法,使用properties的配置文件

我使用的mysql的版本是8.0以上的  driver为com.mysql.cj.jdbc.Driver

以下的版本driver没cj

配置信息如下  类似键值对

user=root
password=iamsorry36
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/labbook09

接着

这里需要有一定io流的知识点

配置文件写好,需要读取

//读取文件
 Properties properties = new Properties();
 properties.load(new FileInputStream("src\\labbook09\\mysql_2.properties"));

然后

读取完了需要获取值

//获得相关属性
user = properties.getProperty("user");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
url = properties.getProperty("url");

将获取的相关属性放入DriverManager.getConnection(url,user,password)

这个时候就是拿到连接了

最后代码结果 


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

public class Utils {
    //静态定义相关属性
    private static String user;
    private static String password;
    private static String url;
    private static String driver;

    //使用静态代码块去初始化
    static {
        try {
            //读取文件
            Properties properties = new Properties();
            properties.load(new FileInputStream("src\\labbook09\\mysql_2.properties"));
            //获得相关属性
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
        } catch (IOException e) {
            //把编写异常改为运行异常
            throw new RuntimeException(e);
        }
    }
    //获取连接
    public static Connection getConnection(){
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url,user,password);
        } catch (SQLException | ClassNotFoundException e) {
            //把编写异常改为运行异常
            throw new RuntimeException(e);
        }
    }

    //关闭资源
    /*
     * 思路分析  需要关闭哪些内容
     * resultset
     * statement 或者 preparestatement
     * connection
     * 如果是executeQ  有结果集 resultset
     * 如果是executeU  有行数返回
     * */
    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        try {
            if(resultSet != null){
                resultSet.close();
            }
            if (statement != null){
                statement.close();
            }
            if (connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            //把编写异常改为运行异常
            throw new RuntimeException(e);
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这猪能飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值