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
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 += '<p>' + 'contents:' + value.contents + '</p>'; data += '<hr />'; } res.send(data); }); }); app.listen(81); console.log('Listening on port 81');
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!