简体   繁体   中英

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'

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());

Is this the package you are using .In that case, I believe you are missing the connect method which as taken from the docs.Also ELOGIN err comes when login fails

const pool = new sql.ConnectionPool({
    user: '...',
    password: '...',
    server: 'localhost',
    database: '...'
})

pool.connect(err => {
    // ...
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM