一、在pom中添加依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
然后同步一下
二、编写代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) {
Connection connection = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
System.out.println("Exception." + e.getMessage());
} finally {
// Close the connection
if (connection != null) {
try {
System.out.println("Success to connection.");
connection.close();
} catch (SQLException e) {
System.out.println("Failed to close connection.");
e.printStackTrace();
}
} else {
System.out.println("Failed to connection.");
}
}
}
}
这是我的数据库名