express连接mysql数据库

安装MySQL包: npm install mysql -s

在根目录下新建一个config/db.js

// MySQL数据库联接配置
var mysql = require('mysql');
var pool = mysql.createPool({
     
	host: 'localhost',
	port: 3306,
	user: 'root',
	password: 'root',
	database: 'node_express'
});
function query(sql, callback) {
     
	pool.getConnection(function(err, connection) {
     
		// Use the connection
		connection.query(sql, function(err, rows) {
     
			callback(err, rows);
			connection.release(); //释放链接
		});
	});
}

// var mysql      = require('mysql');
// var connection = mysql.createConnection({
     
//   host     : 'localhost',
//   user     : 'root',
//   password : '123456',
//   database : 'testdb'
// });
// connection.connect();
// connection.query(sql, function (error, results, fields) {
     
//   if (error) throw error;
//   console.log('The solution is: ', results[0].solution);
// });
// connection.end();

exports.query = query;

调用代码

var db = require('../config/db.js');
router.get('/', function(req, res, next) {
     
	var sql = 'select * from user'
	db.query(sql, function(err, rows) {
     
		if (err) {
     
			res.render('users.html', {
     
				title: 'Express',
				datas: []
			});
		} else {
     
			res.render('users.html', {
     
				title: 'Express',
				datas: rows
			});
		}
	})
});

你可能感兴趣的:(nodejs)