Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i connect from node.js to sql DB?

i tried the following code:


const config = {
server: 'localhost',
database: 'MyDB',
user: *userName*,
password: *password*

const dbPool = new sql.ConnectionPool(config, err => {
 if (err)
   console.log(err)
 else
   console.log("success")
})

i created on the SSMS a user and a login, and did logged in with it to make sure it works. i changed the authentication from windows to SQL server. what am i missing?

I keep get this error message:

Login failed for user 'userNamr'.,

Code: 'ELOGIN'

like image 520
oded bartov Avatar asked May 21 '26 11:05

oded bartov


1 Answers

I think you have entered a wrong username or a user that does not exist but here is the demonstration how you can connect node.js to sql.

PS: make sure you have npm install and proper module for the db engine.

const pg = require("pg"); //replace "pg" with whatever engine you are using such as mssql

const connectionString = {
      user: 'username',
      host: 'localhost',
      database: 'testdb',
      password: 'mypass',
      port: 5432,
    };

const client = new pg.Client(connectionString);
    client.connect();
    client.query(
        'SELECT * from student;'
        ).then(
          res => {
        console.log(res.rows);
    }).finally(() => client.end());
like image 200
xplatypus07 Avatar answered May 23 '26 01:05

xplatypus07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!