In this article, we assume that you have Node.js, NPM and MySQL installed on your system. We will cover installing the Node.js MySQL driver module on your system and a sample program to connect to MySQL using How to connect Node.js with MySQL?.
#Node.js is a popular programming language like PHP and JAVA for web applications. MySQL is also the most popular database used for storing values. The MySQL database driver for Node.js is available under the NPM repository.
Step 1: Install the Node.js MySQL module
The MySQL driver for How to connect Node.js with MySQL? is available under the Node Package Manager (NPM). Use the following command to install the How to connect Node.js with MySQL? MySQL driver on your system.
$ sudo npm install mysql
Step 2: How to connect Node.js with MySQL? program example
The following is a How to connect Node.js with MySQL? program example that connects a How to connect Node.js with MySQL? application with a mysql server. It will display success and error messages based on the connection results and close the connection at the end of the program. Create a javascript file app.js.
$ cd myApp $ vim app.js
And add the following content to the above file.
var mysql = require('mysql'); var dbconn = mysql.createConnection({ host : 'localhost', user : '<DB_USER>', password : '<DB_PASSWORD', database : '<DB_NAME>' }); dbconn.connect(function(err){ if(err){ console.log('Database connection error'); }else{ console.log('Database connection successful'); } }); dbconn.end(function(err) { // 关闭数据库连接的函数 });
Step 3: Verify connection
Now use the command line to execute the How to connect Node.js with MySQL? script and ensure that How to connect Node.js with MySQL? is properly connected to mysql.
$ node app.js Database connection successful
The above is the detailed content of How to connect Node.js with MySQL?. For more information, please follow other related articles on the PHP Chinese website!