This article demonstrates how to connect to a MySQL database using Node.js.
The node-mysql package enables you to easily connect to a MySQL database using Node.js. Before you can do this, however, you must install the node-mysql package on your account. To do this, follow these steps:
cd ~ npm install mysql
After you install the node-mysql package, you are ready to work with actual databases. The following sample Node.js code demonstrates how to do this.
In your own code, replace dbname with the database name, username with the MySQL database username, and password with the database user's password. Additionally, you should modify the SELECT query to match a table in your own database:
var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', database : 'dbname', user : 'username', password : 'password', }); connection.connect(function(err) { if (err) { console.error('Error connecting: ' + err.stack); return; } console.log('Connected as id ' + connection.threadId); }); connection.query('SELECT * FROM employee', function (error, results, fields) { if (error) throw error; results.forEach(result => { console.log(result); }); }); connection.end();
This example creates a MySQL connection object that connects to the MySQL database. After the database connection is established, you can use the query method to run raw SQL statements (in this case, a SELECT query on a table named employee).
For more information about the node-mysql package, please visit https://github.com/mysqljs/mysql.
Subscribe to receive weekly cutting edge tips, strategies, and news you need to grow your web business.
No charge. Unsubscribe anytime.
Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.
We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.