ZF3中的多个DB连接

时间:2018-03-06 21:35:01

标签: database zend-framework3

当我使用ZF1时,我有一个带有数据库连接信息的ini文件(即mysql,pgsql,mssql等等)

modulename.adapter = PDO_MYSQL
modulename.params.host = xxx.xxx.x.xx
modulename.params.username = username
modulename.params.password = password
modulename.params.dbname = databasename

在我的模型中,我会扩展Zend_Db_Table并在我的

中执行以下操作
public function _construct() {
        $dbconfig = Zend_Registry::get('dbProfiles');
        $this->db = Zend_Db::factory($dbconfig->modulename->adapter,
        $dbconfig->modulename->params);         
}

在某些功能中,我有以下代码

$sql = "SELECT * FROM Table";
$result = $this->db->query($sql);
while($row =$result->fetch()) {
//... do something
}            

我如何在ZF3中做类似的事情?连接多种数据库类型,查询不同的表并获取结果?

谢谢。

1 个答案:

答案 0 :(得分:2)

在您的配置中设置与数据库一样多的数据库适配器:

const express = require('express');
const http = require('http');
const WebSocket = require('ws');


const app = express();

app.use(function (req, res) {
  res.send({ msg: "hello" });
});

const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

server.listen(8080, function listening() {
  console.log('Listening on %d', server.address().port);
});

然后调用服务管理器工厂中的适配器来创建tablegateway或者只是将适配器传递给控制器​​:

    'db'    => [
    'adapters'  => [
        'Application\Db\Db1Adapter'   => [
            'driver' => 'Pdo_Mysql',
            'Dsn'   => 'mysql:dbname=Your_db_1_name;host=your_host;charset=utf8',
            'password' => 'your_password',
            'username' => 'your_username',

        ],

        'Application\Db\Db2Adapter' => [
            'driver'    => 'Pdo_Mysql',
            'Dsn'       =>  'mysql:dbname=Your_db_2_name;host=your_host;charset=utf8',
            'password' => 'your_password',
            'username' => 'your_username',


        ]
    ]
],