Skip to content

Commit d3a8d98

Browse files
committed
Merge pull request mysqljs#523 from whoughton/master
expose SqlString.format
2 parents e1fc958 + 5b23a5a commit d3a8d98

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

Readme.md

+12
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,18 @@ connection.query('SELECT * FROM ?? WHERE id = ?', ['users', userId], function(er
498498

499499
When you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL injection in object keys.
500500

501+
### Preparing Queries
502+
503+
You can use mysql.format to prepare a query with multiple insertion points, utilizing the proper escaping for ids and values. A simple example of this follows:
504+
505+
```js
506+
var sql = "SELECT * FROM ?? WHERE ?? = ?";
507+
var inserts = ['users', 'id', userId];
508+
sql = mysql.format(sql, inserts);
509+
```
510+
511+
Following this you then have a valid, escaped query that you can then send to the database safely. This is useful if you are looking to prepare the query before actually sending it to the database. As mysql.format is exposed from SqlString.format you also have the option (but are not required) to pass in stringifyObject and timezone, allowing you provide a custom means of turning objects into strings, as well as a location-specific/timezone-aware Date.
512+
501513
### Custom format
502514

503515
If you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in `.escape()` or any other connection function.

index.js

+1
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,4 @@ exports.createQuery = Connection.createQuery;
2323
exports.Types = Types;
2424
exports.escape = SqlString.escape;
2525
exports.escapeId = SqlString.escapeId;
26+
exports.format = SqlString.format;

0 commit comments

Comments
 (0)