自己写的方法
public static Connection getConn() throws ClassNotFoundException, SQLException {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
String url = "jdbc:mysql://localhost:3306/db1?serverTimezone=UTC";
String username = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
username和password都是自己要连接的数据库的用户名和密码
localhost:3306 我这里连接的是本地数据库 端口号为3306
db1?serverTimezone=UTC&useServerPrepStmts=true
其中:
- db1是我选择的数据库名,要连接哪个数据库就写哪个数据库的名字
- serverTimezone=UTC这里是因为我的数据库版本太高用之前的驱动会 报错,换了驱动之后加上这个参数就可以正常连接了