下载对应版的数据库驱动

  1. #配置文件
  2. url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
  3. user=root
  4. password=123456789
  5. driver=com.mysql.cj.jdbc.Driver
  1. package test;
  2. import java.io.BufferedInputStream;
  3. import java.io.FileInputStream;
  4. import java.sql.Connection;
  5. import java.sql.Driver;
  6. import java.sql.DriverManager;
  7. import java.sql.SQLException;
  8. import java.util.Properties;
  9. public class ConnectionTest {
  10. public static void main(String[] args) throws Exception {
  11. BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("E:\\IdeaProjects\\Demo\\src\\test\\database.properties"));
  12. // 读取配置文件
  13. Properties properties = new Properties();
  14. properties.load(inputStream);
  15. String url = properties.getProperty("url");
  16. String user = properties.getProperty("user");
  17. String password = properties.getProperty("password");
  18. String driverStr = properties.getProperty("driver");
  19. Class.forName(driverStr); // 连接数据库
  20. // 返回Connection对象
  21. Connection driverManager = DriverManager.getConnection(url, user, password);
  22. }
  23. }