Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

nodered mysql

作者:ら非你不取丶   发布日期:2026-05-18   浏览:88

// 导入必要的模块
const mysql = require('mysql');

// 创建 MySQL 连接
const connection = mysql.createConnection({
  host: 'localhost', // 数据库主机地址
  user: 'root',      // 数据库用户名
  password: 'password', // 数据库密码
  database: 'testdb' // 使用的数据库名称
});

// 连接到数据库
connection.connect((err) => {
  if (err) {
    console.error('连接数据库失败: ' + err.stack);
    return;
  }
  console.log('连接数据库成功');
});

// Node-RED 函数节点示例代码
module.exports = function(RED) {
  function MySQLNode(config) {
    RED.nodes.createNode(this, config);
    var node = this;

    node.on('input', function(msg) {
      const query = 'SELECT * FROM users WHERE id = ?'; // 示例查询语句
      connection.query(query, [msg.payload], function(error, results, fields) {
        if (error) {
          node.error('查询失败: ' + error.message, msg);
          return;
        }
        msg.payload = results; // 将查询结果赋值给 msg.payload
        node.send(msg); // 发送消息到下一个节点
      });
    });

    node.on('close', function(done) {
      connection.end(); // 关闭数据库连接
      done();
    });
  }
  RED.nodes.registerType("mysql", MySQLNode);
};

解释说明:

  1. 导入模块:使用 require 导入 MySQL 模块。
  2. 创建连接:配置并创建一个 MySQL 数据库连接。
  3. 连接数据库:尝试连接到数据库,并处理连接成功或失败的情况。
  4. Node-RED 函数节点:定义一个 Node-RED 节点,用于执行 MySQL 查询。
  5. 查询操作:在接收到输入消息时,执行 SQL 查询并将结果发送到下一个节点。
  6. 关闭连接:当节点关闭时,确保关闭数据库连接。

上一篇:mysql判断一个字段包含另一个字段

下一篇:mysql long_query_time

大家都在看

mysql二级索引

mysqlavg函数保留小数

mysql显示表内容

mysql经纬度距离计算

mysql 加密

存储过程mysql

mysql 1265

mysql with语句

mysql时间加减

mysql查询表名,模糊匹配

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站