Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
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.
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();
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.
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.
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.
An easy-to-use MSSQL database connector for NodeJS.
There are some TDS modules which offer functionality to communicate with MSSQL databases but none of them does offer enough comfort - implementation takes a lot of lines of code. So I decided to create this module, that make work as easy as it could without loosing any important functionality.
Extra features:
At the moment it support three TDS modules:
npm install mssql
var sql = require('mssql');
var config = {
user: '...',
password: '...',
server: 'localhost',
database: '...'
}
var connection = new sql.Connection(config, function(err) {
// ... error checks
// Query
var request = new sql.Request(connection); // or: var request = connection.request();
request.query('select 1 as number', function(err, recordset) {
// ... error checks
console.dir(recordset);
});
// Stored Procedure
var request = new sql.Request(connection);
request.input('input_parameter', sql.Int, value);
request.output('output_parameter', sql.Int);
request.execute('procedure_name', function(err, recordsets, returnValue) {
// ... error checks
console.dir(recordsets);
});
});
var sql = require('mssql');
var config = {
user: '...',
password: '...',
server: 'localhost',
database: '...'
}
sql.connect(config, function(err) {
// ... error checks
// Query
var request = new sql.Request();
request.query('select 1 as number', function(err, recordset) {
// ... error checks
console.dir(recordset);
});
// Stored Procedure
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) {
// ... error checks
console.dir(recordsets);
});
});
var config = {
user: '...',
password: '...',
server: 'localhost',
database: '...',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
}
}
### Basic configuration is same for all drivers.
tedious
). Possible values: tedious
or msnodesql
.1433
).10
).0
).30000
).This driver is not part of the default package and must be installed separately by 'npm install msnodesql'. If you are looking for compiled binaries, see node-sqlserver-binary.
Driver={SQL Server Native Client 11.0};Server=#{server},#{port};Database=#{database};Uid=#{user};Pwd=#{password};Connection Timeout=#{timeout};
### node-tds
This driver is not part of the default package and must be installed separately by 'npm install tds'.
## Connectionsvar connection = new sql.Connection({ /* config */ });
### connect(callback)
Create connection to the server.
Arguments
Example
var connection = new sql.Connection({
user: '...',
password: '...',
server: 'localhost',
database: '...'
});
connection.connect(function(err) {
// ...
});
Close connection to the server.
Example
connection.close();
## Requests
var request = new sql.Request(/* [connection] */);
If you ommit connection argument, global connection is used instead.
### execute(procedure, [callback])Call a stored procedure.
Arguments
returnValue
is also accessible as property of recordsets.Example
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) {
// ... error checks
console.log(recordsets.length); // count of recordsets returned by the procedure
console.log(recordsets[0].length); // count of rows contained in first recordset
console.log(returnValue); // procedure return value
console.log(recordsets.returnValue); // same as previous line
console.log(request.parameters.output_parameter.value); // output value
// ...
});
Add an input parameter to the request.
Arguments
undefined
ans NaN
values are automatically converted to null
values.Example
request.input('input_parameter', value);
request.input('input_parameter', sql.Int, value);
JS Data Type To SQL Data Type Map
String
-> sql.VarChar
Number
-> sql.Int
Boolean
-> sql.Bit
Date
-> sql.DateTime
Default data type for unknown object is sql.VarChar
.
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.BigInt);
Add an output parameter to the request.
Arguments
Example
request.output('output_parameter', sql.Int);
Execute the SQL command.
Arguments
Example
var request = new sql.Request();
request.query('select 1 as number', function(err, recordset) {
// ... error checks
console.log(recordset[0].number); // return 1
// ...
});
You can enable multiple recordsets in querries by request.multiple = true
command.
var request = new sql.Request();
request.multiple = true;
request.query('select 1 as number; select 2 as number', function(err, recordsets) {
// ... error checks
console.log(recordsets[0][0].number); // return 1
console.log(recordsets[1][0].number); // return 2
});
## Transactions
Important: always use Transaction
class to create transactions - it ensures that all your requests are executed on one connection. Once you call begin
, a single connection is aquired from the connection pool and all subsequent requests (initialized with the Transaction
object) are executed exclusively on this connection. After you call commit
or rollback
, connection is then released back to the connection pool.
var transaction = new sql.Transaction(/* [connection] */);
If you ommit connection argument, global connection is used instead.
Example
var transaction = new sql.Transaction(/* [connection] */);
transaction.begin(function(err) {
// ... error checks
var request = new sql.Request(transaction);
request.query('insert into mytable (mycolumn) values (12345)', function(err, recordset) {
// ... error checks
transaction.commit(function(err, recordset) {
// ... error checks
console.log("Transaction commited.");
});
});
});
Transaction can also be created by var transaction = connection.transaction();
. Requests can also be created by var request = transaction.request();
.
Begin a transaction.
Arguments
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
// ...
});
Commit a transaction.
Arguments
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
// ...
transaction.commit(function(err) {
//...
})
});
Rollback a transaction.
Arguments
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
// ...
transaction.rollback(function(err) {
//...
})
});
## Metadata
Recordset metadata are accessible trough recordset.columns
property.
var request = new sql.Request();
request.query('select 1 as first, \'asdf\' as second', function(err, recordset) {
console.dir(recordset.columns);
console.log(recordset.columns.first.type === sql.Int); // true
console.log(recordset.columns.second.type === sql.VarChar); // true
});
Columns structure for example above:
{ first: { name: 'first', size: 10, type: { name: 'int' } },
second: { name: 'second', size: 4, type: { name: 'varchar' } } }
## Data Types
sql.BigInt
sql.Decimal
sql.Float
sql.Int
sql.Money
sql.Numeric
sql.SmallInt
sql.SmallMoney
sql.Real
sql.TinyInt
sql.Char
sql.NChar
sql.Text
sql.NText
sql.VarChar
sql.NVarChar
sql.Xml
sql.Date
sql.DateTime
sql.DateTimeOffset
sql.SmallDateTime
sql.Bit
sql.UniqueIdentifier
Binary types as input parameters are only available with Microsoft's native driver.
sql.VarBinary
sql.NVarBinary
sql.Image
## 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 ----------
## Known issues
sql.map.register(String, sql.NVarChar)
.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.
FAQs
Microsoft SQL Server client for Node.js.
The npm package mssql receives a total of 637,789 weekly downloads. As such, mssql popularity was classified as popular.
We found that mssql demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.