Home > Database > Mysql Tutorial > body text

Example of mysql database using Node.js to implement connection function

黄舟
Release: 2017-09-15 11:12:07
Original
1151 people have browsed it

This article mainly introduces the function of Node.js to connect to the mysql database, and briefly analyzes the operation steps and related implementation techniques of nodejs to connect to the database. Friends in need can refer to the following

The examples in this article describe Node. js implements the function of connecting to mysql database. Share it with everyone for your reference, the details are as follows:

Before Node.js connects to the database, you need to install the corresponding package. If you install sql server, you need to install the node-sqlserver package first. We use mysql as an example to illustrate node.js querying mysql data.

1. Install node-mysql


npm install node-mysql
Copy after login

2. Implement database connection through express framework


var express = require('express');
var mysql = require('mysql');
var app = express();
app.use(function(req, res, next){
 console.log('%s %s', req.method, req.url);
 next();
});
var conn = mysql.createConnection({
  host:'localhost',
  user:'root',
  database:'ceshi',
  password:'123456',
  port:3306
});
conn.connect();
app.get('/', function(req, res){
  conn.query('SELECT * from ceshibiao', function(err, rows, fields) {
    if(err) throw err;
    var data = '';
    foreach(rows,function(key,value){
      data += &#39;<p>&#39; + &#39;contents:&#39; + value.contents + &#39;</p>&#39;;
      data += &#39;<hr />&#39;;
    }
    res.send(data);
  });
});
app.listen(81);
console.log(&#39;Listening on port 81&#39;);
Copy after login

The above is the detailed content of Example of mysql database using Node.js to implement connection function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!