What is mssql?
The mssql npm package is a Microsoft SQL Server client for Node.js. It allows you to connect to SQL Server databases, execute queries, and manage transactions. It supports both Promises and async/await syntax, making it versatile for different coding styles.
What are mssql's main functionalities?
Connecting to a SQL Server
This code demonstrates how to connect to a SQL Server database using the mssql package. You need to provide your database credentials and server information in the config object.
const sql = require('mssql');
const config = {
user: 'your_username',
password: 'your_password',
server: 'your_server',
database: 'your_database'
};
async function connectToDatabase() {
try {
let pool = await sql.connect(config);
console.log('Connected to the database');
} catch (err) {
console.error('Database connection failed: ', err);
}
}
connectToDatabase();
Executing a Query
This code demonstrates how to execute a SQL query using the mssql package. It connects to the database and runs a SELECT query on a specified table.
const sql = require('mssql');
const config = {
user: 'your_username',
password: 'your_password',
server: 'your_server',
database: 'your_database'
};
async function executeQuery() {
try {
let pool = await sql.connect(config);
let result = await pool.request().query('SELECT * FROM your_table');
console.log(result);
} catch (err) {
console.error('Query execution failed: ', err);
}
}
executeQuery();
Using Prepared Statements
This code demonstrates how to use prepared statements with the mssql package. Prepared statements are useful for executing queries with parameters, which can help prevent SQL injection attacks.
const sql = require('mssql');
const config = {
user: 'your_username',
password: 'your_password',
server: 'your_server',
database: 'your_database'
};
async function executePreparedStatement() {
try {
let pool = await sql.connect(config);
let ps = new sql.PreparedStatement(pool);
ps.input('input_parameter', sql.Int);
await ps.prepare('SELECT * FROM your_table WHERE id = @input_parameter');
let result = await ps.execute({ input_parameter: 1 });
console.log(result);
await ps.unprepare();
} catch (err) {
console.error('Prepared statement execution failed: ', err);
}
}
executePreparedStatement();
Managing Transactions
This code demonstrates how to manage transactions using the mssql package. Transactions allow you to execute a series of queries as a single unit of work, which can be committed or rolled back based on success or failure.
const sql = require('mssql');
const config = {
user: 'your_username',
password: 'your_password',
server: 'your_server',
database: 'your_database'
};
async function manageTransaction() {
try {
let pool = await sql.connect(config);
let transaction = new sql.Transaction(pool);
await transaction.begin();
let request = new sql.Request(transaction);
await request.query('INSERT INTO your_table (column1) VALUES (value1)');
await transaction.commit();
console.log('Transaction committed');
} catch (err) {
console.error('Transaction failed: ', err);
if (transaction) await transaction.rollback();
}
}
manageTransaction();
Other packages similar to mssql
mysql
The mysql package is a client for MySQL databases. It provides similar functionalities to mssql, such as connecting to a database, executing queries, and managing transactions. However, it is specifically designed for MySQL databases.
pg
The pg package is a PostgreSQL client for Node.js. Like mssql, it allows you to connect to a database, execute queries, and manage transactions. It is tailored for PostgreSQL databases and offers features specific to PostgreSQL.
sqlite3
The sqlite3 package is a client for SQLite databases. It provides functionalities for connecting to SQLite databases, executing queries, and managing transactions. Unlike mssql, it is designed for lightweight, file-based databases.
#node-mssql
An easy-to-use MSSQL database connector for NodeJS.
It's based on awsome TDS module Tedious by Mike D Pilsbury.
Installation
npm install mssql
Getting started
var sql = require('mssql');
sql.pool = {
max: 1,
min: 0,
idleTimeoutMillis: 30000
}
sql.connection = {
userName: '...',
password: '...',
server: 'localhost',
options: {
database: '...'
}
}
sql.init();
Stored procedure call
var request = new sql.Request();
request.input('input_parameter', sql.Int, value);
request.output('output_parameter', sql.Int);
request.execute('procedure_name', function(err, recordsets, returnValue) {
console.log(recordsets.length);
console.log(recordset[0].length);
console.log(returnValue);
console.log(request.parameters.output_parameter.value);
});
Parameters
request.input('input_parameter', value);
request.input('input_parameter', sql.Int, value);
request.output('output_parameter', sql.Int);
If you omit type
argument of input parameter, module automaticaly decide which SQL data type should be used based on JS data type. You can define you own type map.
sql.map.register(MyClass, sql.Text);
You can also overwrite default type map.
sql.map.register(Number, sql.Int);
Default map
String
-> sql.VarChar
Number
-> sql.BigInt
Boolean
-> sql.Bit
Date
-> sql.DateTime
Default data type for unknown object is sql.VarChar
.
Simple query
var request = new sql.Request();
request.query('select 1 as number', function(err, recordset) {
console.log(recordset[0].number);
});
Data types
sql.VarChar
sql.NVarChar
sql.Text
sql.Int
sql.BigInt
sql.TinyInt
sql.SmallInt
sql.Bit
sql.Float
sql.Real
sql.DateTime
sql.SmallDateTime
sql.UniqueIdentifier
Tedious data type constants can be accessed by sql.TYPES.<type>
. Complete list of data type constants can be found here: Tedious Datatypes
Verbose mode
You can enable verbose mode by request.verbose = true
command.
var request = new sql.Request();
request.verbose = true;
request.input('username', 'patriksimek');
request.input('password', 'dontuseplaintextpassword');
request.input('attempts', 2);
request.execute('my_stored_procedure');
Output for example above could look similar to this.
---------- sql execute --------
proc: my_stored_procedure
input: @username, varchar, patriksimek
input: @password, varchar, dontuseplaintextpassword
input: @attempts, bigint, 2
---------- response -----------
{ id: 1,
username: 'patriksimek',
password: 'dontuseplaintextpassword',
email: null,
language: 'en',
attempts: 2 }
---------- --------------------
return: 0
duration: 5ms
---------- completed ----------
License
Copyright (c) 2013 Patrik Simek
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.