NodeJS鏈接mysql數據庫

1,下載mysql

cnpm install mysql

2,引入並配置修改數據庫用戶名密碼及數據庫名sql

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.拋出源碼,蹬蹬蹬~~~~npm

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});
        });
    
});
相關文章
相關標籤/搜索