我在 Sails 应用程序中使用 PostgreSQL 时遇到了类似的问题。一世
在下面找到了解决方法。
即 npm install pg。
在你的情况下安装 mysql 插件,即 npm i mysql
我在sails app controllers 文件夹中创建了dbconnections.js
const a = {
host: 'abc.com',
port: 'xxxx',
database: 'xxxx',
user: 'xxxx',
password: 'xxxx'
}
const b = {
host: 'ecd.com',
port: 'xxxx',
database: 'xxxx',
user: 'xxxx',
password: 'xxxx'
}
module.exports = { a: a, b: b};
然后在我的其他控制器中,我使用 pg 插件来匹配用户传递的 db
环境通过api
即在我的另一个控制器中
var sourceFile = require('./dbconnections.js');
const {
Client
} = require('pg');
对于您的情况,您可以关注https://www.npmjs.com/package/mysql
创建连接对象并按照以下逻辑动态连接
到不同的数据库
var match_env;
for (x in sourceFile) {
if (x === env) {
match_env = sourceFile[x];
}
}
const client = new Client(match_env)
现在客户端对象将拥有所有可以使用的 postgresql 事务
执行,即
客户端.connect()
const qry = "select * from person where city="newyork";
client.query(qry, function (err, resp) {
console.log("before", client)
client.end();
console.log("after", client)
//user = JSON.parse(user);
if (err) {
return res.json({
error: err
});
}
if (resp === undefined) {
return res.notFound();
} else
console.log(resp);
return res.json({
userData: resp.rows
});
}
);
根据用例,我们可以将上面的代码移动到其他 js 文件并调用
作为
尽可能多的控制器,这将与多个用于多个数据库一起使用
Sails 应用中 postgres sql 的连接。