SQL Server多个数据库Node.js连接

时间:2019-05-07 11:06:44

标签: mysql node.js

我想连接到数据库很少的SQL Server。我正在使用用于mysql的mysql库。我想要实现的是连接到SQL Server并基于像这样的发送查询来查询不同的数据库。

SELECT * FROM db1 where id = 1

SELECT * FROM db2 where id = 2

我的代码:

const express = require('express')
const mysql = require('mysql')
const fs = require('fs');
const app = express()

const db = mysql.createConnection({
    host: '',
    user: '',
    password: '',
    database: '' // I want to pass db name in SQL query below not here
})
db.connect()

app.get('/', (req, res) => {
 //and here i want to pass db name in query not in above.
 //so every query that i send will contain db
    const sql = 'SELECT * FROM users'

    db.query(sql, (err, result) => {
        if (err) throw err;
        res.json(result)
    })
})

app.listen(5000, () => {
    console.log('Server started')
})

1 个答案:

答案 0 :(得分:3)

您只需在database对象中省略createConnection属性。 参见Establishing connections

...

const db = mysql.createConnection({
    host: '',
    user: '',
    password: ''
})

db.connect()

...