Code
- MySQL 8.0 以上版本(高版本)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcUtils {
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/book" +
"?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&characterEncoding=utf-8";
private static String name = "root";
private static String pwd = "";
private static Connection con = null;
public static Connection getConnection() {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, name, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return con;
}
public static void close() {
if(con != null) {
try {
con.close();
con = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
- MySQL 8.0 以下版本
(将8.0以上代码作如下修改)
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/book";
jar包
8.0以上版本
8.0以下版本