本教程仅限于 mysql-connectorv8.0.21 + mysql8.0 + jdk1.8

一、在pom.xml中加入JDBC驱动JAR包的依赖项

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.21</version>
</dependency>

二、书写配置文件,并置于resources目录下

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC</property>
        <property name="user">root</property>
        <property name="password">123456</property>
    </default-config>
</c3p0-config>

三、书写JDBC简单工具类

public class JDBCUtils {
    private JDBCUtils(){}
    public static Connection getConnection(String driverClass,String jdbcUrl,String user,String password){
        Connection conn = null;
        try {
            Class.forName(driverClass);
            conn = DriverManager.getConnection(jdbcUrl,user,password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }
}

四、书写代码,是用正则表达式实现xml配置文件解析

public class RegexDemo {
    public static void main(String[] args) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(RegexDemo.class.getClassLoader().getResourceAsStream("c3p0-config.xml"), "UTF-8"));
        String str;
        while((str=br.readLine())!=null){
            sb.append(str);
        }
        Pattern p = compile("<property name=\"(.*?)\">(.*?)</property>");
        Matcher matcher = p.matcher(sb);
        HashMap<String, String> config = new HashMap<String, String>();
        while(matcher.find()){
            config.put(matcher.group(1),matcher.group(2));
        }
        Set<Map.Entry<String, String>> sets = config.entrySet();
        for (Map.Entry<String, String> set : sets) {
            System.out.println(set.getKey()+":"+set.getValue());
        }
        String driverClass = config.get("driverClass");
        String jdbcUrl = URLDecoder.decode(config.get("jdbcUrl"));
        jdbcUrl = jdbcUrl.replaceAll("&amp;","&");
        String user = config.get("user");
        String password = config.get("password");
        Connection conn = JDBCUtils.getConnection(driverClass, jdbcUrl, user, password);
        System.out.println(conn);
    }
}

五、成功获取所需信息,输出结果如下

password:123456
driverClass:com.mysql.cj.jdbc.Driver
jdbcUrl:jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC
user:root
com.mysql.cj.jdbc.ConnectionImpl@49070868

注意:在第四步的时候,我做了一个额外操作,将jdbcUrl中的&amp;转义字符全部转换为&,否则url是错误的,是不上数据库的!

原文作者:絷缘
作者邮箱:zhiyuanworkemail@163.com
原文地址:https://zhiyuandnc.github.io/UBe69VI0p/
版权声明:本文为博主原创文章,转载请注明原文链接作者信息