1

I want to connect to SQL Server where I have few databases. I am using mysql library for nodejs. What I want to achieve is to connect to SQL Server and query different databases based on send query like this.

SELECT * FROM db1 where id = 1

SELECT * FROM db2 where id = 2

etc

My code:

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 Answer 1

4

You can just omit the database attribute in the createConnection object. See Establishing connections

...

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

db.connect()

...
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, can i console.log(db.connect())?? to check if is connected
console.log in general is a bad practise to check variables, just set a breakpoint and use the debugger ( nodejs.org/de/docs/guides/debugging-getting-started ). But you can just inspect the db object there should be a property connected
If my answer helped and fix you problem i would appreciate if you set it as correct answer :)
This answer is related to MySql, whereas the question was specifically about MSSql
the question was tagged as mysql question and in the code example the mysql package was used

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.