To access a MySQL or MariaDB database from within the JavaScript code of a Node-RED function node, you can use the node-red-node-mysql package.
This package provides a Node-RED node that you can use to execute SQL queries and retrieve the results from within your JavaScript code.
To use the node-red-node-mysql node, you will first need to install the package using npm. You can do this by running the following command in your Node-RED installation directory:
npm install node-red-node-mysql
Once the package is installed, you can use the mysql
node in your flow by dragging it from the palette and configuring it with the necessary connection details for your database.
You can then use the mysql
node in your function node by specifying it as an input or output, depending on whether you want to use it to execute queries or retrieve results.
Here is an example of how you can use the mysql
node in your function node to execute a SQL query and retrieve the results:
// Initialize the MySQL node
var mysql = context.get('mysql');
// Define the SQL query to be executed
var sql = 'SELECT * FROM users WHERE id = 1';
// Execute the query and retrieve the results
var result = await mysql.query(sql);
// Use the results in your JavaScript code
msg.payload = result;
Hope this is helpful.