How to use the close function from mssql

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

mssql.close is a function that closes a connection to a Microsoft SQL Server database.

53
54
55
56
57
58
59
60
61
62
await sql.connect(initConnectConfig);
await new sql.Request().query(
  `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)'
fork icon34
star icon66
watch icon0

417
418
419
420
421
422
423
424
425
426
    }
};
return Promise.resolve()
    .then(function () {
        if (sql) {
            return sql.close();
        }
        else
            return Promise.resolve();
    })
fork icon25
star icon55
watch icon21

How does mssql.close work?

mssql.close works by taking a connection object or a pool object as an argument and closing the associated connection(s) to a Microsoft SQL Server database. When a connection or a pool is no longer needed, mssql.close is used to release the resources associated with the connection or the pool, including sockets, database cursors, and memory allocations. The function sends a request to the database server to close the connection and waits for a response. Once the response is received, the function releases any resources associated with the connection and frees up memory. mssql.close is important for preventing resource leaks and ensuring efficient use of system resources. It is recommended to call mssql.close when a connection or a pool is no longer needed or when the application is shutting down. Note that mssql.close can also be used in conjunction with error handling code to ensure that connections are properly closed even in case of errors or exceptions.

78
79
80
81
82
83
84
85
86
            console.error("Could not perform query:", error);
        });
    }

    // clean up connections
    sql.close();
    statsdConn.close();
}).catch(function(err) {
    console.error("Something went wrong with the DB connection: ", err);
fork icon9
star icon11
watch icon1

+ 7 other calls in file

135
136
137
138
139
140
141
142
143
144
        await transaction.commit();
        let t2 = new Date().getTime();
        process.stdout.write("\r\x1b[K");
        process.stdout.write("## " + chalk.yellow(x.toString()) + chalk.green(" record(s) written in " + chalk.yellow((t2 - t1).toString()) + " ms"));
        process.stdout.write("\n## " + chalk.green("Finished SQL Transaction"));
        mssql.close();
        process.stdout.write("\n## " + chalk.green("SQL Connection closed"));
} catch (err) {
        console.error("\n" + chalk.red("ERROR:", err));
}
fork icon5
star icon3
watch icon4

+ 20 other calls in file

Ai Example

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

async function run() {
  try {
    const pool = await sql.connect({
      server: "localhost",
      database: "MyDatabase",
      user: "myUsername",
      password: "myPassword",
    });

    // ... perform database operations ...

    await sql.close();
  } catch (err) {
    console.error(err);
  }
}

run();

In this example, we use the mssql.connect function to create a connection pool to a Microsoft SQL Server database. We then perform some database operations using the pool, such as querying the database, inserting or updating data, and so on. When we are done with the database operations and no longer need the connection pool, we call the sql.close method to close the connection pool and release any resources associated with it. The sql.close method returns a Promise that resolves when the connection pool is closed. We use await to wait for the Promise to resolve before exiting the try block. Note that the mssql library also provides a connection object that can be used to create a single connection to a database, rather than a pool. In this case, mssql.close would be called on the connection object to close the connection, rather than on the sql object.

30
31
32
33
34
35
36
37
38
39
      `SELECT salary, emp_name, bonus, job_id, hire_date
        FROM employee WHERE emp_name = 'Liu Bei' AND salary > 10000
        ORDER BY salary DESC`
    const result = await mssql.query(sql)
    console.log(result.recordset)
    mssql.close()
  } catch (error) {
    console.log(error)
  }
}
fork icon3
star icon6
watch icon3

+ 5 other calls in file

31
32
33
34
35
36
37
38
39
40
        clientObj=result.recordset[0];

}).catch(err => {
        // ... error checks
})
        sql.close()
        return clientObj;
}

async function selectAnimalType(animal){
fork icon0
star icon3
watch icon2

+ 13 other calls in file

55
56
57
58
59
60
61
62
63
64
// catch errors in this block
// fill out empty id's before pushing the sql
let pool = await sql.connect(sqlConfig)
let result = await pool.request()
        .query("SELECT * from dbo.Animals, dbo.VetDetails, dbo.ClientDetails where dbo.Animals.ClientID = dbo.ClientDetails.ClientID and dbo.ClientDetails.VetSurgeryId = dbo.VetDetails.ID")
//if err sql.close
// "SELECT top 1 * from dbo.BookingObjects order by BookingID desc" // returns most recently assigned ID
let bookings = await pool.request()
        .query("SELECT * from dbo.BookingObjects ,dbo.VetDetails, dbo.Animals, dbo.ClientDetails where dbo.Animals.ClientID = dbo.ClientDetails.ClientID and dbo.Animals.AnimalID =  dbo.BookingObjects.AnimalID and dbo.ClientDetails.VetSurgeryId = dbo.VetDetails.ID and dbo.BookingObjects.DateOut > '2017-07-06 12:00:00.000'")
//if err sql.close
fork icon0
star icon3
watch icon3

+ 7 other calls in file

170
171
172
173
174
175
176
177
178
179
//              break;
//      }
//  }).then(result => {

//      return result.recordset;
//      mssql.close();
//  }).catch(err => {
//      console.dir(err);
//      mssql.close();
//  });
fork icon0
star icon1
watch icon1

+ 15 other calls in file

124
125
126
127
128
129
130
131
132
133
            // Clear the worksheet
            for (let j = worksheet.rowCount; j >= 1; j--) {
                worksheet.spliceRows(j, 1);
            }
        }
        yield mssql.close();
        // End of Async
    });
}
runQueryLoop();
fork icon0
star icon1
watch icon1

+ 25 other calls in file

248
249
250
251
252
253
254
255
256
        resolve(new Account(accountWannabe)); //resolve with a new Account object
      } catch (err) {
        reject(err); //reject with error
      }

      sql.close(); //closes DB connection
    })();
  });
}
fork icon0
star icon0
watch icon2

+ 9 other calls in file

12
13
14
15
16
17
18
19
20
21
let config = sqlServer.getConfig( user_id , passwd, db_name ); 
try{
	await sql.connect( config )
	let result_1 = await sql.query( sql_state )
	console.log( result_1.recordset) 
	await sql.close() 
	result.RESULT = 0 
	result.RAWDATA = JSON.parse( JSON.stringify( result_1 ))
	result.DATA = result_1.recordset
        return  result
fork icon0
star icon0
watch icon0

+ 7 other calls in file

51
52
53
54
55
56
57
58
59
60
61
    try{
        await sqlserver.connect(connectString)
    }catch(err){
        throw Error(err.message)
    }
    await sqlserver.close()
    return true
}


async function executeSql(db,sql,params) {
fork icon0
star icon0
watch icon1

32
33
34
35
36
37
38
39
40
41
42
        }).catch(err => {
            // ... error checks
            console.log(err)
            //reject(err)
        }).then(() => {
            //return sql.close()
        })
});



fork icon0
star icon0
watch icon0

+ 15 other calls in file