Learn how to connect n8n to MySQL by setting up the MySQL node, configuring credentials, testing the connection, and performing database operations within your workflows.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Connecting n8n to MySQL involves setting up a MySQL connection node, configuring the database credentials, and testing the connection to ensure n8n can interact with your MySQL database. This allows you to perform operations such as querying data, inserting records, updating tables, and more within your n8n workflows.
Step 1: Prerequisites
Before connecting n8n to MySQL, ensure you have the following:
Step 2: Add a MySQL Node to Your Workflow
Step 3: Configure the MySQL Connection
Once you've added the MySQL node, you need to configure the connection:
Fill in the following connection details:
Click on "Create" to save the credentials.
Step 4: Test the MySQL Connection
After creating the credentials, test the connection to ensure it works properly:
Step 5: Configure the MySQL Operation
Now that you have successfully connected to MySQL, configure the operation you want to perform:
Step 6: Executing a SQL Query (Example)
Let's configure the node to execute a simple SQL query:
SELECT \* FROM customers WHERE country = 'USA' LIMIT 10;
SELECT \* FROM customers WHERE country = '{{$json["country"]}}' LIMIT {{$json["limit"]}};
Step 7: Selecting Data from a Table (Example)
To retrieve data using the Select operation:
Step 8: Inserting Data into a Table (Example)
To insert data into a table:
{{$json["first\_name"]}}
Step 9: Updating Data in a Table (Example)
To update existing records:
id = 5
or email = '{{$json["email"]}}'
Step 10: Deleting Data from a Table (Example)
To delete records:
id = {{$json["id_to_delete"]}}
Step 11: Handling Multiple Queries with Multi-Query Node
If you need to execute multiple SQL statements:
INSERT INTO log (action) VALUES ('start');
UPDATE products SET price = price \* 1.1 WHERE category = 'electronics';
INSERT INTO log (action) VALUES ('end');
Step 12: Working with Query Parameters
For better security and to prevent SQL injection, use parameterized queries:
SELECT \* FROM customers WHERE country = ? AND status = ?;
{{$json["country"]}}
Step 13: Connecting MySQL to Other Nodes
To create a complete workflow:
Step 14: Error Handling for MySQL Operations
Add error handling to your MySQL workflows:
Example function for data validation:
// Check if required fields exist
if (!$input.json["customer\_name"] || !$input.json["email"]) {
return []; // Return empty to stop execution
}
// Sanitize data
const sanitized = {
customer_name: $input.json["customer_name"].trim(),
email: $input.json["email"].toLowerCase().trim()
};
return { json: sanitized };
Step 15: Creating Transactions for Multiple Operations
For operations that need to be executed as a single transaction:
START TRANSACTION;
INSERT INTO orders (customer_id, product_id, quantity) VALUES (42, 101, 2);
UPDATE inventory SET stock = stock - 2 WHERE product\_id = 101;
COMMIT;
START TRANSACTION;
INSERT INTO orders (customer_id, product_id, quantity) VALUES (42, 101, 2);
UPDATE inventory SET stock = stock - 2 WHERE product\_id = 101;
-- Check if stock went negative
SELECT stock FROM inventory WHERE product_id = 101 INTO @current_stock;
-- Rollback if we have negative stock
SET @continue = IF(@current\_stock >= 0, 1, 0);
-- Conditionally commit or rollback
COMMIT AND CHAIN IF @continue = 1;
ROLLBACK IF @continue = 0;
Step 16: Performance Considerations
Optimize your MySQL operations for better performance:
SELECT id, name, email FROM customers
WHERE created\_at > '2023-01-01'
ORDER BY id
LIMIT 100 OFFSET {{$json["page"] \* 100}};
Step 17: Securing Your MySQL Connection
Implement security best practices:
{{$env.N8N_MYSQL_PASSWORD}}
Step 18: Handling Blob and Binary Data
To work with BLOB data types:
INSERT INTO documents (filename, file\_data)
VALUES ('report.pdf', FROM\_BASE64('{{$binary\["data"]\["base64"]}}'));
SELECT id, filename, TO_BASE64(file_data) as file_data_base64
FROM documents WHERE id = 123;
Step 19: Working with JSON Data in MySQL
If your MySQL database (version 5.7+) uses JSON columns:
INSERT INTO user_settings (user_id, preferences)
VALUES (42, '{{JSON.stringify($json["preferences"])}}');
SELECT id, user\_id,
JSON\_EXTRACT(preferences, '$.theme') as theme,
JSON_EXTRACT(preferences, '$.notifications.email') as email_notifications
FROM user_settings WHERE user_id = 42;
Step 20: Troubleshooting Common Issues
If you encounter connection problems:
Database-specific error solutions:
Step 21: Advanced: Using MySQL with Other n8n Features
Combine MySQL with other n8n features for powerful workflows:
Example workflow for database backup notification:
Step 22: Practical Example: Building a Complete MySQL Workflow
Let's build a complete workflow that imports data from an API into MySQL:
https://api.example.com/users
// Transform API data to database format
return $input.json.map(user => {
return {
json: {
user\_id: user.id,
full\_name: `${user.first_name} ${user.last_name}`,
email: user.email.toLowerCase(),
created\_at: new Date().toISOString().slice(0, 19).replace('T', ' ')
}
};
});
Connect the nodes in sequence: HTTP Request → Function → MySQL → Slack
This workflow fetches user data from an API, transforms it to match your database schema, inserts it into your MySQL database, and sends a notification when complete.
Conclusion
You've now learned how to connect n8n to MySQL and perform various database operations. This integration enables you to build powerful workflows that interact with your MySQL database. You can read and write data, execute custom queries, and combine database operations with other n8n nodes for comprehensive automation solutions.
By following this guide, you should be able to incorporate MySQL database interactions into your n8n workflows, whether for data synchronization, reporting, user management, or any other database-related automation task.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.