下载地址: https://dev.mysql.com/downloads/connector/j/.
将下载的jar文件复制到lib目录下
首先进入Project Sttructure
在Dependencies点击加号
选择之前复制到lib目录的mysql驱动进行添加
应用即可。
public class ConnectionTest {
//方式一
@Test
public void testConnection1() throws SQLException {
//初始化驱动
Driver driver = new com.mysql.cj.jdbc.Driver();
//协议(jdbc:mysql) + ip地址(loaclhost) + 端口号(3306) + 数据库(test)
//记得添加东八区时间 serverTimezone=GMT,否则会报异常
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT";
//基本配置,至少包括user和password
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "zq740208");
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
//方式二:对方式一的迭代
@Test
public void testConnection2() throws Exception {
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "zq740208");
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
//方式三:使用DriverManager替代Driver
@Test
public void testConnection3() throws Exception {
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT";
String user = "root";
String password = "zq740208";
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式四:
@Test
public void testConnection4() throws Exception {
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT";
String user = "root";
String password = "zq740208";
//加载Driver
Class.forName("com.mysql.cj.jdbc.Driver");
//省略注册驱动的操作,因为在mysql的Driver类中声明了如下操作:
// static {
// try {
// DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
// } catch (SQLException var1) {
// throw new RuntimeException("Can't register driver!");
// }
// }
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//常用方式
@Test
public void testConnection5() throws Exception {
Properties properties = new Properties();
properties.load(new FileReader("jdbc.properties"));
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);
System.out.println(connection);
}
}



