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-04 13:34  Gazikel  阅读(40)  评论(0编辑  收藏  举报