Java MySQL连接

1.新建一个properties文件,将数据库的配置参数写入

url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
user=root
password=123456
driverClass=com.mysql.cj.jdbc.Driver

2.连接的函数

复制代码
 public static Connection getConnection() throws Exception {
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");

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

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

        Class.forName(driverClass);

        Connection connection = DriverManager.getConnection(url, user, password);

        return connection;
    }
复制代码
posted @ 2020-11-05 21:05  Gqan  阅读(108)  评论(0编辑  收藏  举报