Thanks to visit codestin.com
Credit goes to github.com

Skip to content

brendtumi/mssql

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

node-mssql Dependency Status NPM version

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.

At the moment it support two TDS modules:

Installation

npm install mssql

Quick Example

var sql = require('mssql'); 

config = {
	user: '...',
	password: '...',
	server: 'localhost',
	database: '...'
}

var connection = new sql.Connection(config, function(err) {
	
	// Query
	
	var request = new sql.Request(connection1); // or: var request = connection.request();
	request.query('select 1 as number', function(err, recordset) {
		console.dir(recordset);
	});
	
	// Stored Procedure
	
	var request = new sql.Request(connection1);
	request.input('input_parameter', sql.Int, value);
	request.output('output_parameter', sql.Int);
	request.execute('procedure_name', function(err, recordsets, returnValue) {
		console.dir(recordsets);
	});
	
});

Quick Example with one global connection

var sql = require('mssql'); 

config = {
	user: '...',
	password: '...',
	server: 'localhost',
	database: '...'
}

sql.connect(config, function(err) {
	
	// Query
	
	var request = new sql.Request();
	request.query('select 1 as number', function(err, recordset) {
		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) {
		console.dir(recordsets);
	});
	
});

Documentation

Configuration

Connection

Request

Other

Configuration

config = { ... }
### Basic configuration is same for all drivers.
  • driver - Driver to use (default: tedious). Possible values: tedious or msnodesql.
  • user - User name to use for authentication.
  • password - Password to use for authentication.
  • server - Hostname to connect to.
  • port - Port to connect to (default: 1433).
  • database - Database to connect to (default: dependent on server configuration).
### Tedious
  • options - Tedious specific options. More information: http://pekim.github.io/tedious/api-connection.html
  • pool.max - The maximum number of connections there can be in the pool (default: 10).
  • pool.min - The minimun of connections there can be in the pool (default: 0).
  • pool.idleTimeoutMillis - The Number of milliseconds before closing an unused connection (default: 30000).

Example

config = {
	options: {
		// tedious options
	},
	
	pool: {
		max: 10,
	    min: 0,
	    idleTimeoutMillis: 30000
	}
}
### Microsoft Driver for Node.js for SQL Server

This driver is not part of the default package and you must install it separately.

  • connectionString - Connection string (default: Driver={SQL Server Native Client 11.0};Server=#{server},#{port};Database=#{database};Uid=#{user};Pwd=#{password};).
var connection = new sql.Connection({ /* config */ });
### connect(callback)

Create connection to the server.

Arguments

  • callback(err) - A callback which is called after connection has established, or an error has occurred.

Example

var connection = new sql.Connection({
	user: '...',
	password: '...',
	server: 'localhost',
	database: '...'
});

connection.connect(function(err) {
	// ...
});

### close()

Close connection to the server.

Example

connection.close();
var request = new sql.Request(/* [connection] */);

If you ommit connection argument, global connection is used instead.

### execute(procedure, [callback])

Call a stored procedure.

Arguments

  • procedure - Name of the stored procedure to be executed.
  • callback(err, recordsets, returnValue) - A callback which is called after execution has completed, or an error has occurred.

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) {
	console.log(recordsets.length); // count of recordsets returned by procedure
	console.log(recordset[0].length); // count of rows contained in first recordset
	console.log(returnValue); // procedure return value
	
	console.log(request.parameters.output_parameter.value); // output value
	
	// ...
});

### input(name, [type], value)

Add an input parameter to the request.

Arguments

  • name - Name of the input parameter without @ char.
  • type - SQL data type of input parameter. If you omit type, module automaticaly decide which SQL data type should be used based on JS data type.
  • value - Input parameter value. 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);

### output(name, type)

Add an output parameter to the request.

Arguments

  • name - Name of the output parameter without @ char.
  • type - SQL data type of output parameter.

Example

request.output('output_parameter', sql.Int);

### query(command, [callback])

Execute the SQL command.

Arguments

  • command - T-SQL command to be executed.
  • callback(err, recordset) - A callback which is called after execution has completed, or an error has occurred.

Example

var request = new sql.Request();
request.query('select 1 as number', function(err, recordset) {
	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) {
	console.log(recordsets[0][0].number); // return 1
	console.log(recordsets[1][0].number); // return 2
	
	// ...
});
## 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 ----------
  • UniqueIdentifier testing.
  • Binary, VarBinary, Image testing.
## 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.

About

Copy version 0.3.x of http://patriksimek.cz mssql

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages