Rails 6如何在database.yml数据库配置中添加protocol参数?
问题原因
mysql2适配器不识别你配置的protocol: tcp参数,该参数不是Rails数据库配置的标准生效项。
你连接失败的核心原因是:MySQL客户端默认对localhost域名优先使用Unix套接字建立连接,不会走TCP链路,而你本地的3306是虚拟机端口转发的TCP端口,走套接字自然连接失败。
正确配置方案
方案1(最推荐,无兼容问题)
将host配置从localhost改为127.0.0.1,MySQL客户端遇到IP地址会自动使用TCP协议连接,无需额外加其他参数:
test: adapter: mysql2 encoding: utf8 host: 127.0.0.1 database: mydb_test pool: 5 username: mouser password: mypass variables: sql_mode: NO_ENGINE_SUBSTITUTION
方案2(需保留localhost域名时使用)
添加flags: [:TCP]参数,强制mysql2适配器使用TCP协议建立连接:
test: adapter: mysql2 encoding: utf8 host: localhost database: mydb_test pool: 5 username: mouser password: mypass flags: [:TCP] variables: sql_mode: NO_ENGINE_SUBSTITUTION
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

