Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
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 Node.js / io.js.
Why do you want to use node-mssql?
There is also co wrapper available - co-mssql.
If you're looking for session store for connect/express, visit connect-mssql.
Supported TDS drivers:
node-mssql uses Tedious as the default driver.
npm install mssql
var sql = require('mssql');
var config = {
user: '...',
password: '...',
server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
database: '...',
options: {
encrypt: true // Use this if you're on Windows Azure
}
}
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, 10);
request.output('output_parameter', sql.VarChar(50));
request.execute('procedure_name', function(err, recordsets, returnValue) {
// ... error checks
console.dir(recordsets);
});
});
var sql = require('mssql');
var config = {
user: '...',
password: '...',
server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
database: '...',
options: {
encrypt: true // Use this if you're on Windows Azure
}
}
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.VarChar(50));
request.execute('procedure_name', function(err, recordsets, returnValue) {
// ... error checks
console.dir(recordsets);
});
});
### Streaming example with one global connection
If you plan to work with large amount of rows, you should always use streaming. Once you enable this, you must listen for events to receive data.
var sql = require('mssql');
var config = {
user: '...',
password: '...',
server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
database: '...',
stream: true, // You can enable streaming globally
options: {
encrypt: true // Use this if you're on Windows Azure
}
}
sql.connect(config, function(err) {
// ... error checks
var request = new sql.Request();
request.stream = true; // You can set streaming differently for each request
request.query('select * from verylargetable'); // or request.execute(procedure);
request.on('recordset', function(columns) {
// Emitted once for each recordset in a query
});
request.on('row', function(row) {
// Emitted for each row in a recordset
});
request.on('error', function(err) {
// May be emitted multiple times
});
request.on('done', function(returnValue) {
// Always emitted as the last one
});
});
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
, msnodesql
or tds
.1433
). Don't set when connecting to named instance.15000
).15000
).false
). You can also enable streaming for each request independently (request.stream = true
). Always set to true
if you plan to work with large amount of rows.10
).0
).30000
).true
).false
) Encryption support is experimental.7_4
, available: 7_1
, 7_2
, 7_3_A
, 7_3_B
, 7_4
).XACT_ABORT
during the initial SQL phase of a connection.More information about Tedious specific options: http://pekim.github.io/tedious/api-connection.html
### Microsoft Driver for Node.js for SQL ServerThis 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.
false
).true
).Default connection string when connecting to port:
Driver={SQL Server Native Client 11.0};Server={#{server},#{port}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};
Default connection string when connecting to named instance:
Driver={SQL Server Native Client 11.0};Server={#{server}\\#{instance}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};
### node-tds
This driver is not part of the default package and must be installed separately by npm install tds
.
This module updates the node-tds driver with extra features and bug fixes by overriding some of its internal functions. If you want to disable this, require module with var sql = require('mssql/nofix')
.
var connection = new sql.Connection({ /* config */ });
Errors
ConnectionError
) - Unknown driver.close
).Create connection to the server.
Arguments
Example
var connection = new sql.Connection({
user: '...',
password: '...',
server: 'localhost',
database: '...'
});
connection.connect(function(err) {
// ...
});
Errors
ConnectionError
) - Login failed.ConnectionError
) - Connection timeout.ConnectionError
) - Database is already connected!ConnectionError
) - Already connecting to database!ConnectionError
) - Instance lookup failed.ConnectionError
) - Socket error.Close connection to the server.
Example
connection.close();
## Requests
var request = new sql.Request(/* [connection] */);
If you omit connection argument, global connection is used instead.
Call a stored procedure.
Arguments
returnValue
is also accessible as property of recordsets. Optional. If omited, returns Promise.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
// ...
});
Errors
RequestError
) - Message from SQL ServerRequestError
) - Canceled.RequestError
) - Request timeout.RequestError
) - No connection is specified for that request.ConnectionError
) - Connection not yet open.ConnectionError
) - Connection is closed.TransactionError
) - Transaction has not begun.TransactionError
) - Transaction was aborted (by user or because of an error).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.NVarChar
Number
-> sql.Int
Boolean
-> sql.Bit
Date
-> sql.DateTime
Buffer
-> sql.VarBinary
sql.Table
-> sql.TVP
Default data type for unknown object is sql.NVarChar
.
You can define your own type map.
sql.map.register(MyClass, sql.Text);
You can also overwrite the default type map.
sql.map.register(Number, sql.BigInt);
Errors (synchronous)
RequestError
) - Invalid number of arguments.RequestError
) - SQL injection warning.Add an output parameter to the request.
Arguments
undefined
and NaN
values are automatically converted to null
values. Optional.Example
request.output('output_parameter', sql.Int);
request.output('output_parameter', sql.VarChar(50), 'abc');
Errors (synchronous)
RequestError
) - Invalid number of arguments.RequestError
) - SQL injection warning.Sets request to stream
mode and pulls all rows from all recordsets to a given stream.
Arguments
Example
var request = new sql.Request();
request.pipe(stream);
request.query('select * from mytable');
stream.on('error', function(err) {
// ...
});
stream.on('finish', function() {
// ...
});
Version
2.0
Execute the SQL command. To execute commands like create procedure
or if you plan to work with local temporary tables, use batch instead.
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
// ...
});
Errors
RequestError
) - Request timeout.RequestError
) - Message from SQL ServerRequestError
) - Canceled.RequestError
) - No connection is specified for that request.ConnectionError
) - Connection not yet open.ConnectionError
) - Connection is closed.TransactionError
) - Transaction has not begun.TransactionError
) - Transaction was aborted (by user or because of an error).You can enable multiple recordsets in queries with the 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
});
Execute the SQL command. Unlike query, it doesn't use sp_executesql
, so is not likely that SQL Server will reuse the execution plan it generates for the SQL. Use this only in special cases, for example when you need to execute commands like create procedure
which can't be executed with query or if you're executing statements longer than 4000 chars on SQL Server 2000. Also you should use this if you're plan to work with local temporary tables (more information here).
NOTE: Table-Valued Parameter (TVP) is not supported in batch.
Arguments
Example
var request = new sql.Request();
request.batch('create procedure #temporary as select * from table', function(err, recordset) {
// ... error checks
});
Errors
RequestError
) - Request timeout.RequestError
) - Message from SQL ServerRequestError
) - Canceled.RequestError
) - No connection is specified for that request.ConnectionError
) - Connection not yet open.ConnectionError
) - Connection is closed.TransactionError
) - Transaction has not begun.TransactionError
) - Transaction was aborted (by user or because of an error).You can enable multiple recordsets in queries with the request.multiple = true
command.
Perform a bulk insert.
Arguments
sql.Table
instance.Example
var table = new sql.Table('table_name'); // or temporary table, e.g. #temptable
table.create = true;
table.columns.add('a', sql.Int, {nullable: true});
table.columns.add('b', sql.VarChar(50), {nullable: false});
table.rows.add(777, 'test');
var request = new sql.Request();
request.bulk(table, function(err, rowCount) {
// ... error checks
});
IMPORTANT: Always indicate whether the column is nullable or not!
TIP: If you set table.create
to true
, module will check if the table exists before it start sending data. If it doesn't, it will automatically create it.
TIP: You can also create Table variable from any recordset with recordset.toTable()
.
Errors
RequestError
) - Table name must be specified for bulk insert.RequestError
) - Request timeout.RequestError
) - Message from SQL ServerRequestError
) - Canceled.RequestError
) - No connection is specified for that request.ConnectionError
) - Connection not yet open.ConnectionError
) - Connection is closed.TransactionError
) - Transaction has not begun.TransactionError
) - Transaction was aborted (by user or because of an error).Cancel currently executing request. Return true
if cancellation packet was send successfully.
Example
var request = new sql.Request();
request.query('waitfor delay \'00:00:05\'; select 1 as number', function(err, recordset) {
console.log(err instanceof sql.RequestError); // true
console.log(err.message); // Canceled.
console.log(err.code); // ECANCEL
// ...
});
request.cancel();
## 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 acquired from the connection pool and all subsequent requests (initialized with the Transaction
object) are executed exclusively on this connection. Transaction also contains a queue to make sure your requests are executed in series. After you call commit
or rollback
, connection is then released back to the connection pool.
var transaction = new sql.Transaction(/* [connection] */);
If you omit 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();
.
Aborted transactions
This example shows how you should correctly handle transaction errors when abortTransactionOnError
(XACT_ABORT
) is enabled. Added in 2.0.
var transaction = new sql.Transaction(/* [connection] */);
transaction.begin(function(err) {
// ... error checks
var rolledBack = false;
transaction.on('rollback', function(aborted) {
// emited with aborted === true
rolledBack = true;
});
var request = new sql.Request(transaction);
request.query('insert into mytable (bitcolumn) values (2)', function(err, recordset) {
// insert should fail because of invalid value
if (err) {
if (!rolledBack) {
transaction.rollback(function(err) {
// ... error checks
});
}
} else {
transaction.commit(function(err) {
// ... error checks
});
}
});
});
Begin a transaction.
Arguments
READ_COMMITTED
by default. For possible values see sql.ISOLATION_LEVEL
.Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
// ... error checks
});
Errors
ConnectionError
) - Connection not yet open.TransactionError
) - Transaction has already begun.Commit a transaction.
Arguments
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
// ... error checks
transaction.commit(function(err) {
// ... error checks
})
});
Errors
TransactionError
) - Transaction has not begun.TransactionError
) - Can't commit transaction. There is a request in progress.Rollback a transaction. If the queue isn't empty, all queued requests will be canceled and the transaction will be marked as aborted.
Arguments
Example
var transaction = new sql.Transaction();
transaction.begin(function(err) {
// ... error checks
transaction.rollback(function(err) {
// ... error checks
})
});
Errors
TransactionError
) - Transaction has not begun.TransactionError
) - Can't rollback transaction. There is a request in progress.IMPORTANT: always use PreparedStatement
class to create prepared statements - it ensures that all your executions of prepared statement are executed on one connection. Once you call prepare
, a single connection is aquired from the connection pool and all subsequent executions are executed exclusively on this connection. Prepared Statement also contains a queue to make sure your executions are executed in series. After you call unprepare
, the connection is then released back to the connection pool.
var ps = new sql.PreparedStatement(/* [connection] */);
If you omit the connection argument, the global connection is used instead.
Example
var ps = new sql.PreparedStatement(/* [connection] */);
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err) {
// ... error checks
ps.execute({param: 12345}, function(err, recordset) {
// ... error checks
ps.unprepare(function(err) {
// ... error checks
});
});
});
IMPORTANT: Remember that each prepared statement means one reserved connection from the pool. Don't forget to unprepare a prepared statement!
TIP: You can also create prepared statements in transactions (new sql.PreparedStatement(transaction)
), but keep in mind you can't execute other requests in the transaction until you call unprepare
.
Add an input parameter to the prepared statement.
Arguments
Example
ps.input('input_parameter', sql.Int);
ps.input('input_parameter', sql.VarChar(50));
Errors (synchronous)
PreparedStatementError
) - Invalid number of arguments.PreparedStatementError
) - SQL injection warning.Add an output parameter to the prepared statement.
Arguments
Example
ps.output('output_parameter', sql.Int);
ps.output('output_parameter', sql.VarChar(50));
Errors (synchronous)
PreparedStatementError
) - Invalid number of arguments.PreparedStatementError
) - SQL injection warning.Prepare a statement.
Arguments
Example
var ps = new sql.PreparedStatement();
ps.prepare('select @param as value', function(err) {
// ... error checks
});
Errors
ConnectionError
) - Connection not yet open.PreparedStatementError
) - Statement is already prepared.TransactionError
) - Transaction has not begun.Execute a prepared statement.
Arguments
Example
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err) {
// ... error checks
ps.execute({param: 12345}, function(err, recordset) {
// ... error checks
console.log(recordset[0].value); // return 12345
});
});
You can enable multiple recordsets by ps.multiple = true
command.
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err) {
// ... error checks
ps.multiple = true;
ps.execute({param: 12345}, function(err, recordsets) {
// ... error checks
console.log(recordsets[0][0].value); // return 12345
});
});
You can also stream executed request.
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err) {
// ... error checks
ps.stream = true;
request = ps.execute({param: 12345});
request.on('recordset', function(columns) {
// Emitted once for each recordset in a query
});
request.on('row', function(row) {
// Emitted for each row in a recordset
});
request.on('error', function(err) {
// May be emitted multiple times
});
request.on('done', function(returnValue) {
// Always emitted as the last one
});
});
Errors
PreparedStatementError
) - Statement is not prepared.RequestError
) - Request timeout.RequestError
) - Message from SQL ServerRequestError
) - Canceled.Unprepare a prepared statement.
Arguments
Example
var ps = new sql.PreparedStatement();
ps.input('param', sql.Int);
ps.prepare('select @param as value', function(err, recordsets) {
// ... error checks
ps.unprepare(function(err) {
// ... error checks
});
});
Errors
PreparedStatementError
) - Statement is not prepared.Before you can start using CLI, you must install mssql
globally with npm install mssql -g
. Once you do that you will be able to execute mssql
command.
Setup
Create a .mssql.json
configuration file (anywhere). Structure of the file is the same as the standard configuration object.
{
"user": "...",
"password": "...",
"server": "localhost",
"database": "..."
}
Example
echo "select * from mytable" | mssql /path/to/config
Results in:
[[{"username":"patriksimek","password":"tooeasy"}]]
You can also query for multiple recordsets.
echo "select * from mytable; select * from myothertable" | mssql
Results in:
[[{"username":"patriksimek","password":"tooeasy"}],[{"id":15,"name":"Product name"}]]
If you omit config path argument, mssql will try to load it from current working directory.
Version
2.0
## Geography and Geometrynode-mssql has built-in serializer for Geography and Geometry CLR data types.
select geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326)
select geometry::STGeomFromText('LINESTRING (100 100 10.3 12, 20 180, 180 180)', 0)
Results in:
{ srid: 4326,
version: 1,
points: [ { x: 47.656, y: -122.36 }, { x: 47.656, y: -122.343 } ],
figures: [ { attribute: 1, pointOffset: 0 } ],
shapes: [ { parentOffset: -1, figureOffset: 0, type: 2 } ],
segments: [] }
{ srid: 0,
version: 1,
points:
[ { x: 100, y: 100, z: 10.3, m: 12 },
{ x: 20, y: 180, z: NaN, m: NaN },
{ x: 180, y: 180, z: NaN, m: NaN } ],
figures: [ { attribute: 1, pointOffset: 0 } ],
shapes: [ { parentOffset: -1, figureOffset: 0, type: 2 } ],
segments: [] }
## Table-Valued Parameter (TVP)
Supported on SQL Server 2008 and later. You can pass a data table as a parameter to stored procedure. First, we have to create custom type in our database.
CREATE TYPE TestType AS TABLE ( a VARCHAR(50), b INT );
Next we will need a stored procedure.
CREATE PROCEDURE MyCustomStoredProcedure (@tvp TestType readonly) AS SELECT * FROM @tvp
Now let's go back to our Node.js app.
var tvp = new sql.Table()
// Columns must correspond with type we have created in database.
tvp.columns.add('a', sql.VarChar(50));
tvp.columns.add('b', sql.Int);
// Add rows
tvp.rows.add('hello tvp', 777); // Values are in same order as columns.
You can send table as a parameter to stored procedure.
var request = new sql.Request();
request.input('tvp', tvp);
request.execute('MyCustomStoredProcedure', function(err, recordsets, returnValue) {
// ... error checks
console.dir(recordsets[0][0]); // {a: 'hello tvp', b: 777}
});
TIP: You can also create Table variable from any recordset with recordset.toTable()
.
You can retrieve a Promise when you omit a callback argument.
var connection = new sql.Connection(config);
connection.connect().then(function() {
var request = new sql.Request(connection);
request.query('select * from mytable').then(function(recordset) {
// ...
}).catch(function(err) {
// ...
});
}).catch(function(err) {
// ...
});
Native Promise is returned by default. You can easily change this with sql.Promise = require('myownpromisepackage')
.
Version
2.0
## ErrorsThere are 4 types of errors you can handle:
Those errors are initialized in node-mssql module and its original stack may be cropped. You can always access original error with err.originalError
.
SQL Server may generate more than one error for one request so you can access preceding errors with err.precedingErrors
.
Each known error has code
property.
Type | Code | Description |
---|---|---|
ConnectionError | ELOGIN | Login failed. |
ConnectionError | ETIMEOUT | Connection timeout. |
ConnectionError | EDRIVER | Unknown driver. |
ConnectionError | EALREADYCONNECTED | Database is already connected! |
ConnectionError | EALREADYCONNECTING | Already connecting to database! |
ConnectionError | ENOTOPEN | Connection not yet open. |
ConnectionError | EINSTLOOKUP | Instance lookup failed. |
ConnectionError | ESOCKET | Scoket error. |
ConnectionError | ECONNCLOSED | Connection is closed. |
TransactionError | ENOTBEGUN | Transaction has not begun. |
TransactionError | EALREADYBEGUN | Transaction has already begun. |
TransactionError | EREQINPROG | Can't commit/rollback transaction. There is a request in progress. |
TransactionError | EABORT | Transaction has been aborted. |
RequestError | EREQUEST | Message from SQL Server. Error object contains additional details. |
RequestError | ECANCEL | Canceled. |
RequestError | ETIMEOUT | Request timeout. |
RequestError | EARGS | Invalid number of arguments. |
RequestError | EINJECT | SQL injection warning. |
RequestError | ENOCONN | No connection is specified for that request. |
PreparedStatementError | EARGS | Invalid number of arguments. |
PreparedStatementError | EINJECT | SQL injection warning. |
PreparedStatementError | EALREADYPREPARED | Statement is already prepared. |
PreparedStatementError | ENOTPREPARED | Statement is not prepared. |
SQL errors (RequestError
with err.code
equal to EREQUEST
) contains additional details.
Recordset metadata are accessible through the recordset.columns
property.
var request = new sql.Request();
request.query('select convert(decimal(18, 4), 1) as first, \'asdf\' as second', function(err, recordset) {
console.dir(recordset.columns);
console.log(recordset.columns.first.type === sql.Decimal); // true
console.log(recordset.columns.second.type === sql.VarChar); // true
});
Columns structure for example above:
{ first: { index: 0, name: 'first', length: 17, type: [sql.Decimal], scale: 4, precision: 18 },
second: { index: 1, name: 'second', length: 4, type: [sql.VarChar] } }
## Data Types
You can define data types with length/precision/scale:
request.input("name", sql.VarChar, "abc"); // varchar(3)
request.input("name", sql.VarChar(50), "abc"); // varchar(50)
request.input("name", sql.VarChar(sql.MAX), "abc"); // varchar(MAX)
request.output("name", sql.VarChar); // varchar(8000)
request.output("name", sql.VarChar, "abc"); // varchar(3)
request.input("name", sql.Decimal, 155.33); // decimal(18, 0)
request.input("name", sql.Decimal(10), 155.33); // decimal(10, 0)
request.input("name", sql.Decimal(10, 2), 155.33); // decimal(10, 2)
request.input("name", sql.DateTime2, new Date()); // datetime2(7)
request.input("name", sql.DateTime2(5), new Date()); // datetime2(5)
List of supported data types:
sql.Bit
sql.BigInt
sql.Decimal ([precision], [scale])
sql.Float
sql.Int
sql.Money
sql.Numeric ([precision], [scale])
sql.SmallInt
sql.SmallMoney
sql.Real
sql.TinyInt
sql.Char ([length])
sql.NChar ([length])
sql.Text
sql.NText
sql.VarChar ([length])
sql.NVarChar ([length])
sql.Xml
sql.Time ([scale])
sql.Date
sql.DateTime
sql.DateTime2 ([scale])
sql.DateTimeOffset ([scale])
sql.SmallDateTime
sql.UniqueIdentifier
sql.Binary
sql.VarBinary ([length])
sql.Image
sql.UDT
sql.Geography
sql.Geometry
To setup MAX length for VarChar
, NVarChar
and VarBinary
use sql.MAX
length.
This module has built-in SQL injection protection. Always use parameters to pass sanitized values to your queries.
var request = new sql.Request();
request.input('myval', sql.VarChar, '-- commented');
request.query('select @myval as myval', function(err, recordset) {
console.dir(recordset);
});
## 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 the 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
config.options.tdsVersion = '7_1'
(issue)set language 'English';
.Copyright (c) 2013-2015 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 747,722 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.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.