spring mysql 配置_[spring-boot] 配置 MySQL

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=

在数据库中,新建一张表,放入一丢丢的数据(注意:设计表时,要改表的字符集,排序规则,否则乱码)

5fa599bbb2b39ed39b29b0ccb5257dbe.png

在项目中DemoApplication启动类中增加以下代码

packagecom.example.demo;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.jdbc.core.JdbcTemplate;importjava.util.List;importjava.util.Map;

@SpringBootApplicationpublic classDemoApplication {public static voidmain(String[] args) {

ConfigurableApplicationContext context= SpringApplication.run(DemoApplication.class, args);

JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);

List> result = jdbcTemplate.queryForList("SELECT * FROM student");

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=

重新启动后,白浅女神已经被查询出来打印在控制台了。

2958cacf26b6cafe869c02cdb1567038.png

个人笔记,仅供参考,如有问题,请指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值