Connecting MySQL to Node.js for Database Management
As a beginner in Node.js transitioning from PHP, you may wonder how to integrate MySQL with your Node.js applications. To facilitate this task, multiple Node.js modules are available to assist you.
Recommended Modules:
Various modules offer effective MySQL integration for Node.js users. Some notable options include:
Sample Usage with node-mysql:
Integrating MySQL with Node.js using node-mysql is relatively straightforward. Here's an example code snippet:
// Import the node-mysql module const mysql = require('mysql'); // Establish a connection to the MySQL database const connection = mysql.createConnection({ host: 'example.org', user: 'bob', password: 'secret', }); // Connect to the database connection.connect((err) => { if (err) throw err; console.log("Connected!"); }); // Execute a query const query = connection.query('INSERT INTO posts SET ?', { id: 1, title: 'Hello MySQL' }, (err, result) => { if (err) throw err; console.log("Inserted successfully."); console.log(query.sql); });
This code snippet demonstrates the process of connecting to the database, establishing a connection, executing a query, and logging the result. You can customize these parameters based on your database configuration and specific use case.
The above is the detailed content of How Can I Connect MySQL to My Node.js Application?. For more information, please follow other related articles on the PHP Chinese website!