第一种:直接创建driver对象
//1、注册驱动
Driver driver = new Driver();//创建driver对象
//2、得到连接
String url = "jdbc:mysql://localhost:3306/books?serverTimezone=UTC";
//将用户名和密码放入Properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connect = driver.connect(url, properties);//进行连接
第二种:利用反射获取driver对象
//1、注册驱动
//利用反射加载driver类
Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver)aClass.newInstance();
//2、得到连接
String url = "jdbc:mysql://localhost:3306/books?serverTimezone=UTC";
//将用户名和密码放入Properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connect = driver.connect(url, properties);//进行连接
第三种:使用DriverManager注册驱动
//1、注册驱动
//利用反射加载driver类
Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver)aClass.newInstance();
//2、得到连接
String url = "jdbc:mysql://localhost:3306/books?serverTimezone=UTC";
//将用户名和密码放入Properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
DriverManager.registerDriver(driver);//注册driver驱动
Connection connect = DriverManager.getConnection(url, properties);//进行连接
第四种:不需要创建driver对象,在反射加载完成后,就可以直接调用静态方法建立连接
//1、注册驱动
//利用反射加载driver类
//在加载过程中就完成了driver类的注册
Class.forName("com.mysql.cj.jdbc.Driver");
//2、得到连接
String url = "jdbc:mysql://localhost:3306/books?serverTimezone=UTC";
//将用户名和密码放入Properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//不需要注册驱动就可以直接调用静态方法
Connection connect = DriverManager.getConnection(url, properties);//进行连接
(推荐)第五种:将必要信息放入配置文件中,通过加载配置文件,得到所有信息
//获取配置文件中的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String root = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//注册驱动
Class.forName(driver);
//建立连接
Connection connection = DriverManager.getConnection(url, root, password);