JDBC
引入配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
配置yml文件
spring:
datasource:
username: root
password: root
url: jdbc:mysql://36.1.52.145:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
测试过程中,这里报了一个错:
Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
很明显,是驱动不对,是因为链接MySQL8需要新的驱动,替换为提示中的 com.mysql.cj.jdbc.Driver就可以了。
真的可以了吗?在Test中写个试试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot06DataJdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
System.out.println("数据源" + dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println("链接" + connection);
connection.close();
}
}
然鹅鹅鹅,还是有报错:
java.sql.SQLException: null, message from server: "Host '3W0FICZL7685QS5' is not allowed to connect to this MySQL server"
据说是MySql不允许远程链接,或者是3306端口没有打开,还是密码错了?不管怎么的,开始解决:
使用sql命令查看
use mysql ;
select user,host,password from user;
这里注意一下
mysql5.7以上是没有password这个字段了,取而代之的是authentication_string
我们这里查看user和对应的host得到:
通过命令吧root用户的host改为%
update user set host = '%' where user='root';
select user,host,authentication_string from user;
再次查看
应该可以了,但试试还是报错,网上找了个方法:
授权,并把root用户的密码也改为了root
grant all privileges on *.* to root@'%' identified by "root" with grant option;
刷新授权
flush privileges;
完成后,在Navicat上使用ip测试连接成功了,但执行代码里的Test,又看到了另一个错:
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.
提示系统时区出现错误,可以在mysql中执行命令:
set global time_zone='+8:00'
然后终于可以看到没有error的测试结果了
数据源class com.alibaba.druid.pool.DruidDataSource
log4j:WARN No appenders could be found for logger (druid.sql.Connection).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
2020-07-15 14:43:42.836 INFO 13996 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
链接com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@561b7d53
这里有几个WARN,本着程序员的强迫症精神,搞掉他,借鉴别人的经验之谈,是缺失了一个log4j.properties文件,自己创建一个,放在application.yml同级目录下,具体内容为:
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
到这一步,jdbc链接数据库的坑算是踩完了,截图为证:
网友评论