简体   繁体   English

如何从 node.js 连接到 sql DB?

[英]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.我在 SSMS 上创建了一个用户和一个登录名,并使用它登录以确保它正常工作。 i changed the authentication from windows to SQL server.我将身份验证从 Windows 更改为 SQL 服务器。 what am i missing?我错过了什么?

I keep get this error message:我不断收到此错误消息:

Login failed for user 'userNamr'.用户“userNamr”登录失败 , ,

Code: 'ELOGIN'代码:'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.我认为您输入了错误的用户名或不存在的用户,但这里演示了如何将 node.js 连接到 sql。

PS: make sure you have npm install and proper module for the db engine. PS:确保你有 npm install 和适当的模块用于数据库引擎。

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这是您正在使用的包。在这种情况下,我相信您缺少从文档中获取的连接方法。此外,登录失败时也会出现 ELOGIN 错误

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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