How to use the connect function from mssql

Find comprehensive JavaScript mssql.connect code examples handpicked from public code repositorys.

mssql.connect establishes a new connection to a Microsoft SQL Server.

55
56
57
58
59
60
61
62
63
64
}

async () => {
 try {
  // make sure that any items are correctly URL encoded in the connection string
  await sql.connect(sqlConfig)
  const result = await sql.query`select * from mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // ... error checks
fork icon463
star icon0
watch icon85

+ 29 other calls in file

1
2
3
4
5
6
7
8
9
10
const got = require('got');
const axios = require("axios");
const TurndownService = require('turndown');

async function main() {
  var sqlconnection = await sql.connect(database_config);
  const db_request = new sql.Request();

  const [stackData, dbData, caiCredentials] = await Promise.all([get_stackQuestions(), get_dbData(db_request), get_caiCredentials()]);
  var update_all_questions = false;
fork icon67
star icon145
watch icon18

+ 5 other calls in file

How does mssql.connect work?

mssql.connect is a method in the mssql module in Node.js that establishes a connection with a SQL Server database by creating a new connection pool or reusing an existing one. When called, it takes an object with connection configuration options as a parameter and returns a Promise that resolves to a ConnectionPool object.

55
56
57
58
59
60
61
62
63
64
  `IF EXISTS (SELECT * FROM sys.databases WHERE name = N'${dbName}') DROP DATABASE ${dbName}`
);
await new sql.Request().query(`CREATE DATABASE ${dbName}`);
await sql.close();

pool = await sql.connect(connectConfig);
await new sql.Request().query(
  'CREATE TABLE UserTable (id INT IDENTITY(1,1), name VARCHAR(40) NOT NULL, email VARCHAR(40) NOT NULL)'
);
await new sql.Request().batch(
fork icon34
star icon66
watch icon0

+ 3 other calls in file

430
431
432
433
434
435
436
437
438
439
        message: 'Closed present sql connections, will try connecting to given database',
        options,
        sqlConfig,
        functionName: 'validateMSSQLDatabase'
    });
    return sql.connect(sqlConfig);
})
.then(function (res) {
    logger.debug({
        message: 'Database connected successfully, will update in Integration Model',
fork icon25
star icon55
watch icon21

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const sql = require("mssql");

async function connectToDb() {
  try {
    await sql.connect({
      user: "username",
      password: "password",
      server: "localhost",
      database: "mydb",
    });
    console.log("Connected to database successfully!");
  } catch (err) {
    console.error("Error while connecting to database:", err);
  }
}

connectToDb();

This code creates an async function connectToDb that uses mssql.connect to establish a connection to a SQL Server database. The function takes no arguments and returns a Promise that resolves when the connection is established successfully, or rejects with an error if there was a problem connecting. The connect method is called with an object containing the connection configuration, including the username, password, server name, and database name. Once the connection is established, a success message is logged to the console.

1
2
3
4
5
6
7
8
9
10
const sql = require('mssql');


async function getOrders() {
    try {
        let pool = await sql.connect(config);
        let products = await pool.request().query("SELECT * from Orders");
        return products.recordsets;
    }
    catch (error) {
fork icon46
star icon49
watch icon3

+ 5 other calls in file

1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
	} else
		pools_cache[self.$conn] = self.options;
} else
	self.options = pools_cache[self.$conn];

//self.db = new database.connect(self.options, function(err) {
self.db = new database.ConnectionPool(self.options, function(err) {
	if (err) {
		if (!self.errors)
			self.errors = self.isErrorBuilder ? new global.ErrorBuilder() : [];
fork icon22
star icon48
watch icon0

33
34
35
36
37
38
39
40
41
42
const mssql = require('mssql');

async function getCatalog() {
  console.log('using database ');

  let pool = await mssql.connect(sqlConfig);
  let result = await pool.request()
    .query(`SELECT * FROM dbo.Icecreams ORDER BY [Id]`);

  return result.recordset;
fork icon33
star icon38
watch icon22

+ 3 other calls in file

23
24
25
26
27
28
29
30
31
32

var connectToDatabase = function(datasource, database) {
    var conStr = getConfig(datasource, database);
    var defer = Q.defer();

    var connection = sql.connect(conStr, function(err) {
        if(err){
            defer.reject({code:500, message: utils.format('Error connecting to Sql Server: {0}, database: {1}', datasource, database)});
        }
        else{
fork icon9
star icon13
watch icon11

+ 15 other calls in file

28
29
30
31
32
33
34
35
36
37
}


public getClientsByFilter(filter: string) : Promise<any>
{
    return sql.connect(sqlConfig).then((pool:any) => {
        return pool.request()
            .input("searchcriteria", sql.VarChar(40), filter)
            .execute("getFilteredClients")
    });
fork icon20
star icon11
watch icon2

+ 3 other calls in file

26
27
28
29
30
31
32
33
34
35

function executar(instrucao) {
    // VERIFICA A VARIÁVEL DE AMBIENTE SETADA EM app.js
    if (process.env.AMBIENTE_PROCESSO == "producao") {
        return new Promise(function (resolve, reject) {
            sql.connect(sqlServerConfig).then(function () {
                return sql.query(instrucao);
            }).then(function (resultados) {
                console.log(resultados);
                resolve(resultados.recordset);
fork icon0
star icon10
watch icon1

+ 13 other calls in file

14
15
16
17
18
19
20
21
22
23
pool: null,
createConnection: async function() {
  if (this.pool == null) {
    try {
      console.log('creating connection');
      this.pool = await sql.connect(config);
      this.isConnected = true;
    } catch (error) {
      console.log(error);
      this.isConnected = false;
fork icon0
star icon4
watch icon2

17
18
19
20
21
22
23
24
25
26
const sql = require('mssql')

async () => {
    try {
        // make sure that any items are correctly URL encoded in the connection string
        await sql.connect('mssql://username:password@localhost/database')
        const result = await sql.query`select * from mytable where id = ${value}`
        console.dir(result)
    } catch (err) {
        // ... error checks
fork icon463
star icon1
watch icon2

+ 3 other calls in file

5
6
7
8
9
10
11
12
13
14
if (reporter.options.store.provider !== 'mssql' && reporter.options.blobStorage.provider !== 'mssql') {
  definition.options.enabled = false
  return
}

const pool = await sql.connect(definition.options.uri || definition.options)

if (reporter.options.blobStorage.provider === 'mssql') {
  const blobsTable = definition.options.prefix + 'Blob'
  reporter.blobStorage.registerProvider({
fork icon200
star icon0
watch icon56

+ 11 other calls in file

13
14
15
16
17
18
19
20
21
22
  if (userDomainMatch) {
    this.config.domain = userDomainMatch[1];
    this.config.user = userDomainMatch[2];
  }

  this.connection = await sql.connect(this.config);
}

async execute(query) {
  const result = await this.connection.request().query(query);
fork icon3
star icon35
watch icon5

+ 13 other calls in file

10
11
12
13
14
15
16
17
18
19
        log: options.options.logging
    });
}

_cmdExecStmnt(requestId, sqlStr, inputs) {
    return sql.connect(Object.assign(this.options, this.poolConfig))
        .then((pool) => {   // global pool
            if (!this.pool) {
                this.pool = pool;
            }
fork icon12
star icon41
watch icon6

+ 11 other calls in file

81
82
83
84
85
86
87
88
89
// Return method that does the actual logging
return function (loggingEvent) {

    try {

        mssql.connect(cfg.connSettings).then(function () {

            // Construct the query based on configuration
            var query = cfg.commandText;
fork icon2
star icon1
watch icon1

+ 11 other calls in file

54
55
56
57
58
59
60
61
62
63
64
65
66
67


app.get('/getPointsInPolygon', function (req, res) {
    // mudar para post e assim enviar um polígono para o servidor repl.it


    //conexão com o banco
    sql.connect(config, function (err) {


        if (err) console.log(err);


        // criar requirisão
fork icon0
star icon1
watch icon1

+ 87 other calls in file

102
103
104
105
106
107
108
109
110
111
            database: 'databasename',
            options: {
                encrypt: false
            }
        };
        yield mssql.connect(dbConfig);
        for (let i = 0; i < QueryConditionArray.length; i++) {
            var SQL = ` // Your SQL query goes here
${QueryConditionArray[i]}`;
            const result = yield mssql.query(SQL);
fork icon0
star icon1
watch icon1

+ 25 other calls in file

51
52
53
54
55
56
57
58
59
60
         SERIESNUM το τελευταιο παραστατικο+1 απο το κατω query και αν δε βρει τιποτα 
         FINCODE βάζω το όνομα της παραγγελίας
 
 */

 await mssql.connect(config);

 getRq()
     .query(`
select findoc,TRNDATE,FISCPRD,PERIOD,FINCODE,BRANCH,int01 as paragomeno,int02 as pos_parag
fork icon0
star icon1
watch icon1

+ 6 other calls in file

7
8
9
10
11
12
13
14
15
16
    IF NOT EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='IHP_Ivc' AND COLUMN_NAME ='emailed_voucher')
    BEGIN
    ALTER TABLE IHP_Ivc ADD emailed_voucher [smallint] NULL
    END
`
sql.connect(sqlConfig, err=>{
    if(err){
        reject(`Can't connect to database\n${err}`);
    }else{
        new sql.Request().query(query, (err, result)=>{
fork icon1
star icon0
watch icon0