环境: mysql8.0
1导入jar包
jar下载链接:MySQL :: Download Connector/Jhttps://dev.mysql.com/downloads/connector/j/
将下载的jar包放到bin下
连接数据库并进行测试
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TEST01 {
@Test
public void test01() throws SQLException, ClassNotFoundException {
//0.添加jar
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.建立连接
//使用jdbc连接mysql 地址是本机 端口号是3306的test库
String url ="jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useSSL=false";
//用户名
String user="root";
//密码
String password="123456";
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
//3.创建命令发送器
Statement statement = connection.createStatement();
//4.准备sql
//insert into users values(null,"杜甫","123456");
String sql ="insert into users values (null,'李白','test')";
//5.执行sql 获取结果
int i = statement.executeUpdate(sql);
//6.输出结果
System.out.println(i>0?"添加成功":"添加失败");
//7.关闭资源
statement.close();
connection.close();
}
}
报错解决:
(1)Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
无事务连接异常,无法创建连接。将MySQL驱动改为了最新的8.0版本的MySQL驱动。显示那个驱动类已经过时了,新的驱动类是"com.mysql.cj,jdbc.Driver”,而不是“com.mysql.jdbc.Driver"了,并且还说我没有配置时区,查了一下,原来从JDBC6.0开始驱动类使用了新的,并且url中必须要设置时区,否侧会报错。
将Class.forName("com.mysql.jdbc.Driver");改为Class.forName("com.mysql.cj.jdbc.Driver");
(2)java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
没有配置时区,查了一下,原来从JDBC6.0开始驱动类使用了新的,并且url中必须要设置时区,否侧会报错。
将URL改为:String url ="jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding-utf8&serverTimezone=Asia/Shanghai;