sqlstring
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
SqlString is a robust npm package that enables simple SQL escape and formatting geared towards MySQL. It offers an invaluable defense line against SQL Injection attacks by providing methods to safely escape any user-supplied data before it's used in a SQL query. Furthermore, SqlString can format your queries with multiple insertion points while correctly handling the escaping for identifiers and values.
To use SqlString, you first need to install the package using npm with the command npm install sqlstring
. Then, you can import the package into your JavaScript code via var SqlString = require('sqlstring');
.
To escape query values, you can utilize the SqlString.escape()
method this way:
var userId = 'user input';
var sql = 'SELECT * FROM users WHERE id = ' + SqlString.escape(userId);
console.log(sql); // Outputs: SELECT * FROM users WHERE id = 'user input'
SqlString also supports the usage of ?
as placeholders for values that you want to have escaped:
var userId = 1;
var sql = SqlString.format('SELECT * FROM users WHERE id = ?', [userId]);
console.log(sql); // Outputs: SELECT * FROM users WHERE id = 1
You can even use SqlString.raw()
to form SQL queries with functions:
var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()');
var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]);
console.log(sql); // Outputs: UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42
Escaping query identifiers can be done with SqlString.escapeId(identifier)
, and you can also use ??
as placeholders for identifiers you need to have escaped.
The SqlString.format
can be used to prepare a query with multiple insertion points:
var userId = 1;
var inserts = ['users', 'id', userId];
var sql = SqlString.format('SELECT * FROM ?? WHERE ?? = ?', inserts);
console.log(sql); // Outputs: SELECT * FROM `users` WHERE `id` = 1
The documentation of SqlString can be found in the README file of the package, available on the SqlString Github repository. The README file provides a comprehensive overview of how to use various functions of SqlString, how to install it, and other crucial information about the package. The Github repository serves as the primary source of documentation for SqlString, making it easier for developers to utilize the package to its full potential.