纠正Ruby on Rails Database.yml fi的MySQL配置

我有这个配置:

development:
  adapter: mysql2
  encoding: utf8
  database: my_db_name
  username: root
  password: my_password
  host: mysql://127.0.0.1:3306

我收到这个错误:

Unknown MySQL server host 'mysql://127.0.0.1:3306' (1)

有什么明显的东西我做错了吗?

GeekedOut asked 2019-09-10T14:07:00Z
6个解决方案
190 votes

您应该将主机与端口号分开。你可以有一些东西,比如:

development:
  adapter: mysql2
  encoding: utf8
  database: my_db_name
  username: root
  password: my_password
  host: 127.0.0.1
  port: 3306
Amokrane Chentir answered 2019-09-10T14:07:14Z
16 votes

你也可以这样做:

default: &default
  adapter: mysql2
  encoding: utf8
  username: root
  password:
  host: 127.0.0.1
  port: 3306

development:
  <<: *default
  database: development_db_name

test:
  <<: *default
  database: test_db_name

production:
  <<: *default
  database: production_db_name
pangpang answered 2019-09-10T14:07:38Z
2 votes

如果你可以有一个空的config / database.yml文件然后定义ENV ['DATABASE_URL']变量,那么它会工作

$ cat config/database.yml
 
$ echo $DATABASE_URL
mysql://root:my_password@127.0.0.1:3306/my_db_name

对于Heroku:heroku config:set DATABASE_URL='mysql://root:my_password@host.com/my_db_name'

user3118220 answered 2019-09-10T14:08:12Z
1 votes

使用'utf8mb4'作为编码来覆盖所有unicode(包括表情符号)

default: &default
  adapter: mysql2
  encoding: utf8mb4
  collation: utf8mb4_bin
  username: <%= ENV.fetch("MYSQL_USERNAME") %>
  password: <%= ENV.fetch("MYSQL_PASSWORD") %>
  host:     <%= ENV.fetch("MYSQL_HOST") %>

(参考值1)(给定2)

botibs answered 2019-09-10T14:08:44Z
0 votes

如果您有多个数据库用于测试和开发,这可能会有所帮助

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
Rick answered 2019-09-10T14:09:10Z
0 votes

这些通道都没有为我工作,我发现Werner Bihl的答案解决了这个问题。

在为Ruby on Rails应用程序设置mysql数据库时出现“无法通过套接字连接到本地MySQL服务器'/var/run/mysqld/mysqld.sock'”错误

t q answered 2019-09-10T14:09:41Z
translate from https://stackoverflow.com:/questions/5872264/correct-mysql-configuration-for-ruby-on-rails-database-yml-file