maven 测试连接数据库
package com.xiang.lesson01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBTest {
private static String URL = "jdbc:mysql://localhost:3307/webapp1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false";
private static String DriverClass = "com.mysql.cj.jdbc.Driver";
private static String UserName = "webapp1";
private static String PassWord = "webapp1";
private static Connection connection = null;
public static Connection getConnection() {
try {
Class.forName(DriverClass);
connection = DriverManager.getConnection(URL, UserName, PassWord);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
// public void closeRerource(Connection connection){
// try {
// connection.close();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// }
public static void closeRerource() {
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void main(String[] args) {
connection = DBTest.getConnection();
if (connection != null) {
System.out.println("连接成功");
} else {
System.out.println("连接失败");
}
closeRerource();
}
}
配置依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
运行结果