Home >Database >Mysql Tutorial >How to connect Node.js with MySQL?

How to connect Node.js with MySQL?

不言
不言Original
2019-03-06 11:41:172254browse

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?.

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     : &#39;<DB_USER>&#39;,
  password : &#39;<DB_PASSWORD&#39;,
  database : &#39;<DB_NAME>&#39;
});
dbconn.connect(function(err){
  if(err){
    console.log(&#39;Database connection error&#39;);
  }else{
    console.log(&#39;Database connection successful&#39;);
  }
});
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn