我想连接到数据库很少的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')
})
答案 0 :(得分:3)
您只需在database
对象中省略createConnection
属性。
参见Establishing connections
...
const db = mysql.createConnection({
host: '',
user: '',
password: ''
})
db.connect()
...