Home  >  Article  >  Web Front-end  >  Node.js realizes the method of connecting to mysql database

Node.js realizes the method of connecting to mysql database

巴扎黑
巴扎黑Original
2017-09-18 09:50:431782browse

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 connecting Node.js to the database, you need to install the corresponding package. If you install sql server, you need to install the package node-sqlserver first. We use mysql as an example to illustrate node.js querying mysql data.

1. Install node-mysql


npm install node-mysql

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;);

The above is the detailed content of Node.js realizes the method of connecting to mysql database. 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