Home >Database >Mysql Tutorial >How Can I Connect to MySQL Databases Using Node.js?
Connecting to MySQL with Node.js
As a seasoned PHP developer transitioning to Node.js, you may be wondering how to leverage your MySQL expertise in your new environment. Here's how you can seamlessly connect to MySQL with Node.js:
1. Choose a MySQL Module
Node.js offers several modules that facilitate MySQL connectivity. Some popular options include:
2. Establishing a Connection
Once you've selected a module, establishing a connection to MySQL is straightforward using the following syntax:
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'example.org', user: 'bob', password: 'secret', }); connection.connect(function(err) { // Do something... });
3. Executing Queries
Querying data in MySQL is just as simple. Here's how to insert a record using the connection.query() method:
var post = { id: 1, title: 'Hello MySQL' }; var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) { // Handle errors or results here... }); console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
The above is the detailed content of How Can I Connect to MySQL Databases Using Node.js?. For more information, please follow other related articles on the PHP Chinese website!