1,下载
cnpm install mysql
2,引入并配置修改数据库用户名密码及数据库名
var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '123456', database : 'test' }); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution); });
3,如果本地数据库连接失败,报错10061,说明本地MySQL服务未启动,在我的电脑右键服务下启动mysql
4.抛出源码,蹬蹬蹬~~~~
var Mysqlconnect = require('mysql'); var sql = Mysqlconnect.createConnection({ host:'localhost', user:'root', password:'xxxx', database:'trip' }); sql.connect(); /* GET users listing. */ router.get('/', function(req, res, next) { sql.query("select * from tour",[],function(err,data){ console.log(data); res.send(data); }); }); // 登录 router.post('/login', function(req, res, next) { console.log(req.body.username); sql.query("select * from user_app where username = ? and password = ?",[req.body.username,req.body.password],function(err,data){ console.log(data); if(err){ console.log(err); return; } res.send(data); }); }); // 注册 router.post('/register', function(req, res, next) { console.log(req.body.username); sql.query("insert into user_app (username,password,phone) value (?,?,?)",[req.body.username,req.body.password,req.body.phone],function(err,data){ console.log(data); if(err){ console.log(err); return; } res.json({res_code:0}); }); });