• NodeJS连接mysql数据库


    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});
            });
        
    });
  • 相关阅读:
    Kvm --01 虚拟化基础概念
    Git--09 创建Maven项目
    Git--08 Jenkins
    Git--07 Gitlab备份与恢复
    Git --06 Git-gui安装
    Git --05 Gitlab使用
    Git--04 Github使用
    socket 释放全过程
    动态规划习题总结
    linux heap堆分配
  • 原文地址:https://www.cnblogs.com/blog-zy/p/10953609.html
Copyright © 2020-2023  润新知