1
0
mirror of https://github.com/node-red/node-red-nodes.git synced 2023-10-10 13:36:58 +02:00

MySQL allows to pass named parameters as object (#565)

* add check isobj

* added example to readme.md

* edit if Syntax

* add Documentation link to readme.md

* fixed Syntax and edit readme.md
This commit is contained in:
Marco 2020-04-10 23:53:17 +02:00 committed by GitHub
parent dfda66f415
commit 0351441075
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 1 deletions

View File

@ -123,7 +123,23 @@ module.exports = function(RED) {
node.on("input", function(msg) {
if (node.mydbConfig.connected) {
if (typeof msg.topic === 'string') {
var bind = Array.isArray(msg.payload) ? msg.payload : [];
//console.log("query:",msg.topic);
var bind = [];
if (Array.isArray(msg.payload)) { bind = msg.payload; }
else if (typeof msg.payload === 'object' && msg.payload !== null) {
bind=msg.payload;
node.mydbConfig.connection.config.queryFormat = function (query, values) {
if (!values){
return query;
}
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
}
node.mydbConfig.connection.query(msg.topic, bind, function(err, rows) {
if (err) {
status = {fill:"red",shape:"ring",text:"Error: "+err.code};

View File

@ -27,3 +27,26 @@ If nothing is found for the key then <i>null</i> is returned.
The reconnect retry timeout in milliseconds can be changed by adding a line to <b>settings.js</b>
<pre>mysqlReconnectTime: 30000,</pre></p>
Preparing Queries
-----
```javascript
msg.payload=[24, 'example-user'];
msg.topic="INSERT INTO users (`userid`, `username`) VALUES (?, ?);"
return msg;
```
with named parameters:
```javascript
msg.payload={}
msg.payload.userToChange=42;
msg.payload.newUsername="example-user";
msg.topic="INSERT INTO users (`userid`, `username`) VALUES (:userToChange, :newUsername) ON DUPLICATE KEY UPDATE `username`=:newUsername;"
return msg;
```
Documentation
-----
<a href="https://www.npmjs.com/package/mysql" target="_new">Documentation</a> of the used Node.js package