node连接sql数据库

秦禄
2023-12-01
var sql = require('mssql'); 
var dbConfig = {
    user: 'sa',
    password: 'sa123456789',
    server: 'localhost',
    database: 'test',
    port: 1433,
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
    },
    options:{
        encrypt: false
    }
  };
// 
function getAllUsers() {
    var conn = new sql.ConnectionPool(dbConfig);
    var req = new sql.Request(conn);
    conn.connect(function (err) {
        if (err) {
            console.log(err);
            return;
        }
        req.query("SELECT *  FROM [test].[dbo].[tes]", function (err, recordset) {
            console.log(err);
            if (err) {
                console.log(err);
                return;
            }
            else {
                console.log(recordset);
            }
            conn.close();
        });
    });
}
    getAllUsers();
var express = require('express');
var app = express();
var sql = require("mssql");

const sqlStr = "SELECT *  FROM [test].[dbo].[tes]"

app.get('/', function (req, res) {
    // config for your database
    var config = {
        user: 'sa',  // update me
        password: 'sa123456789',   // update me
        server: 'localhost',  // update me
        database: 'test',   // update me
        encrypt:false   //  不加上这个会报错:connect error
    };

    // connect to your database
    sql.connect(config, function (err) {
        if (err) () => {console.log(err);return}
        // create Request object
        var request = new sql.Request();
        // query to the database and get the records
        request.query(sqlStr, function (err, recordset) {
            if (err) console.log(err)
            // send records as a response
            res.send(recordset);
        });
    });
});

var server = app.listen(5152, function () {
    console.log('Server is running in ↓');
    console.log('localhost:5152');
});

 类似资料: