Unknown MySQL server host 'localhost' 问题

本地mvn clean install  出现Unknown MySQL server host 'localhost' 问题

异常日志:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImpl': Unsatisfied dependency expressed through method 'setSqlSession' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionTemplate' defined in class path resource [com/-/boot/autoconfigure/mybatis/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionTemplate' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in class path resource [com/youzan/boot/autoconfigure/mybatis/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSource' defined in com.youzan.ebiz.orm.domain.UserDaoTest$Config: Unsatisfied dependency expressed through method 'dataSource' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mysqlServer' defined in com.-.ebiz.orm.domain.UserDaoTest$Config: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.youzan.ebiz.test.MysqlServer]: Factory method 'mysqlServer' threw exception; nested exception is com.wix.mysql.exceptions.CommandFailedException: Command 'CREATE USER 'user'@'%' IDENTIFIED BY 'password';' on schema 'information_schema' failed with errCode '1' and output 'mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)

原因:

连接mysql数据库的时候会出现:mysql error 2005 - Unknown MySQL server host 'localhost'(0)错误;
当检查连接信息,连接属性信息,用户名和密码都是正确的,IP地址为:localhost,在有网络的情况下都能正常打开数据库,但是一断网就出错了。

解决:

在创建mysql连接的时候在主机或IP地址一栏填写:127.0.0.1而不要填写localhost,然后在断网的情况下进行测试会发现是可以连接成功的。 错误原因是:在有网络的情况,会自动解析localhost为127.0.0.1,而断网的情况下,localhost只是一个字符串,不代表一个ip地址。 mysql配置文件的存储在hosts文件中,其位置在: Windows:c:\windows\system32\drives\etc\hosts Linux:/etc/hosts 打开配置文件可看到在文件的末尾处,localhost的主机ip设置为127.0.0.1。

苹果Mac OS系统修改Hosts文件的方法 : https://laod.cn/hosts/mac-os-xiugai-hosts.html