在 strapi 中连接到 MySql 数据库

Connecting to MySql DB in strapi

我似乎无法理解 http://strapi.io/documentation/configuration#databases

中的文档

如何连接MySqlDB?我在 databases.json 中的哪个位置设置所有数据库设置,例如用户:root、密码:secret123、主机:192.12.2.123 等?

您应该像这样添加一个新连接:

{
  "orm": {
    "adapters": {
      "mysql": "sails-mysql"
    },
    "defaultConnection": "default",
    "connections": {
      "someMysqlServer": {
        "adapter": "mysql",
        "host": "YOUR_MYSQL_SERVER_HOSTNAME_OR_IP_ADDRESS",
        "user": "YOUR_MYSQL_USER",
        "password": "YOUR_MYSQL_PASSWORD",
        "database": "YOUR_MYSQL_DB"
      }
    }
  }
}

Strapi 的当前版本基于 Waterline,因此如果您在文档中找不到正确的信息,请同时查看 Waterline/Sails 文档。

MySQL adapter for the Sails framework and Waterline ORM. Allows you to use MySQL via your models to store and retrieve data. Also provides a query() method for a direct interface to execute raw SQL commands.

从 NPM 安装。

在您的应用中:

$ npm install sails-mysql

风帆配置

将 mysql 配置添加到 config/connections.js 文件。基本选项:

module.exports.connections = {
  mysql: {
    module    : 'sails-mysql',
    host      : 'localhost',
    port      : 3306,
    user      : 'username',
    password  : 'password',
    database  : 'MySQL Database Name'

    // OR (explicit sets take precedence) 
    module    : 'sails-mysql',
    url       : 'mysql2://USER:PASSWORD@HOST:PORT/DATABASENAME'

    // Optional 
    charset   : 'utf8',
    collation : 'utf8_swedish_ci'
  }
};

然后将默认模型配置更改为 config/models.js:

module.exports.models = {
  connection: 'mysql'
};

运行 测试

您可以设置环境变量来覆盖测试的默认数据库配置,例如:

$ WATERLINE_ADAPTER_TESTS_PASSWORD=yourpass npm test
Default settings are:

{
  host: process.env.WATERLINE_ADAPTER_TESTS_HOST || 'localhost',
  port: process.env.WATERLINE_ADAPTER_TESTS_PORT || 3306,
  user: process.env.WATERLINE_ADAPTER_TESTS_USER || 'root',
  password: process.env.WATERLINE_ADAPTER_TESTS_PASSWORD || '',
  database: process.env.WATERLINE_ADAPTER_TESTS_DATABASE || 'sails_mysql',
  pool: true,
  connectionLimit: 10,
  waitForConnections: true
}

参考:https://www.npmjs.com/package/sails-mysql

2020 年的解决方案

  1. 添加客户:
  • Strapi < 3.2.5: yarn add sails-mysqlnpm install sails-mysql
  • Strapi >= 3.2.5: yarn add mysqlnpm install mysql
  1. 更改配置 <project>/config/database.js(用于开发)或 <project>/config/env/production/database.js(用于生产)
module.exports = ({ env }) => ({
  defaultConnection: 'default',
  connections: {
    default: {
      connector: 'bookshelf',
      settings: {
        client: "mysql",
        host: env('DATABASE_HOST', 'localhost'),
        port: env('DATABASE_PORT', 3306),
        database: env('DATABASE_NAME', 'default'),
        username: env('DATABASE_USERNAME', 'root'),
        password: env('DATABASE_PASSWORD', ''),
      },
      options: {
        useNullAsDefault: true,
      },
    },
  },
});
  1. 您可能还需要 运行 yarn build 重建您的 CMS。