作者:可怜小淖_135 | 来源:互联网 | 2023-09-06 22:17
spring-boot项目 配置MYSQL驱动
maven pom文件中增加依赖
mysql
mysql-connector-java
runtime
在application.properties中加入配置(注:我的密码数据库密码是空)
#MYSQL链接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
在数据库中,新建一张表,放入一丢丢的数据(注意:设计表时,要改表的字符集,排序规则,否则乱码)
![[spring-boot] 配置 MySQL [spring-boot] 配置 MySQL](https://img1.php1.cn/3cd4a/24ed6/978/47363bf101207141.png)
在项目中DemoApplication启动类中增加以下代码
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);
List);
System.out.println(result);
}
}
重新启动程序
报错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.
正在加载类“com.mysql.jdbc.driver”。这已被弃用。新的驱动程序类是'com.mysql.cj.jdbc.driver'。驱动程序通过SPI自动注册,通常不需要手动加载驱动程序类。
报错原因:mysql5用的驱动url是com.mysql.jdbc.Driver,mysql6以后用的是com.mysql.cj.jdbc.Driver。版本不匹配便会报驱动类已过时的错误。
解决方案:更改MySQL的驱动配置(注:以下代码标红部分)
#MYSQL链接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
重新启动:
报错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.
java.sql.sqlException:服务器时区值“”无法识别或代表多个时区。如果要利用时区支持,必须配置服务器或JDBC驱动程序(通过ServerTimeZone配置属性),以使用更具体的时区值。
错误原因:在MYSQL6以后,要需要指定时区serverTimezone。
解决方案:在数据库连接后增加服务时区,时区有很多,可以根据自己的需要自行配置
#MYSQL链接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezOne=UTC
spring.datasource.username=root
spring.datasource.password=
重新启动后,白浅女神已经被查询出来打印在控制台了。
![[spring-boot] 配置 MySQL [spring-boot] 配置 MySQL](https://img1.php1.cn/3cd4a/24ed6/978/f3f1a8153354ea4d.png)
个人笔记,仅供参考,如有问题,请指正。