node.js 调用mysql 数据库

1、在package.json中添加mysql依赖

命令:npm install mysql --save

2、项目中添加mysql文件夹

> 文件夹下创建config文件夹,并在config下创建index.js写入mysql配置文件

const mysql = require('mysql')

const connectdb=()=>{
  let connection = mysql.createConnection({
    host     : 'localhost',
    port     : '3306',
    user     : 'root',
    password : '',
    database : 'rehab'
  }) 
  return connection;
}

module.exports=connectdb;
mysql 配置

> mysql文件夹下创建mysql.js文件

const conn = require('./config/index');
const connection = conn();

// 查询所有数据
let selectAll = async(sql,callback)=>{
  return sqlQuery(sql)
}
let selectBy = async(table,where,callback)=>{
    var _WHERE='';
    // var keys='';
    // var values='';
    for(var k2 in where){
        _WHERE+=k2+"='"+where[k2]+"' AND ";
      //_WHERE+= k2+"='"+where[k2]+"'";
    }
    _WHERE=_WHERE.slice(0,-5)
    // UPDATE user SET Password='321' WHERE UserId=12
    //update table set username='admin2',age='55'   where id="5";
    var sql="SELECT * FROM "+table+' WHERE '+_WHERE;
   // console.log(sql);
    return sqlQuery(sql)
}
// 插入一条数据
let insertData =async (table,datas,callback)=>{
  var fields='';
  var values='';
  for( var k in datas){
      fields+=k+',';
      values=values+"'"+datas[k]+"',"
  }
  fields=fields.slice(0,-1);
  values=values.slice(0,-1);
 // console.log(fields,values);
  var sql="INSERT INTO "+table+'('+fields+') VALUES('+values+')';
  return sqlQuery(sql)
}

/**
 * 更新一条数据
 * @param {*} table 数据表名
 * @param {*} sets 更新字段
 * @param {*} where 限制条件
 */
let updateData=async function(table,sets,where){
    var _SETS='';
    var _WHERE='';
    var keys='';
    var values='';
    for(var k in sets){
        _SETS+=k+"='"+sets[k]+"',";
    }
    _SETS=_SETS.slice(0,-1);
    for(var k2 in where){
        _WHERE+=k2+"='"+where[k2]+"' AND ";
      //_WHERE+= k2+"='"+where[k2]+"'";
    }
    _WHERE=_WHERE.slice(0,-5)
    // UPDATE user SET Password='321' WHERE UserId=12
    //update table set username='admin2',age='55'   where id="5";
    var sql="UPDATE "+table+' SET '+_SETS+' WHERE '+_WHERE;
   // console.log(sql);
    return sqlQuery(sql)
}

// 删除一条数据
let deleteData=function(table,where,callback){
    var _WHERE='';
    for(var k2 in where){
       _WHERE+=k2+"='"+where[k2]+"' AND ";
      //_WHERE+= k2+"="+where[k2];
    }
    _WHERE=_WHERE.slice(0,-5)
    // DELETE  FROM user WHERE UserId=12  注意UserId的数据类型要和数据库一致
    var sql="DELETE  FROM "+table+' WHERE '+_WHERE;
   // connection.query(sql,callback);
    return sqlQuery(sql)
}

let sqlQuery=function(sql){
  return new Promise((resolve,reject)=>{
    connection.query(sql,(err,result)=>{
      if(err){
          console.log('错误信息-',err.sqlMessage);
          let errNews = err.sqlMessage;
          reject(errNews)
      } else{
        resolve(result)
      }
    })
  })
}
module.exports = {
  selectAll,
  selectBy,
  insertData,
  deleteData,
  updateData,
}
mysql帮助类

3、创建api文件,调用mysql数据库

let util = require('../utils/util')
const db = require('../mysql/mysql.js')
var logger = require('log4js').getLogger("index");
let util_http = require('../utils/util_http')


module.exports = {

    /**
     * 根据数据表名查询全部
     */
    'GET /mysql/findAll': async (ctx, next) => {
        ctx.response.type = 'application/json';

        let table = ctx.request.query.table
        let sql = `select * from ${table}`
        await db.selectAll(sql).then(res => {
            ctx.body = util.res(res)
        }).catch(err => {
            ctx.body = util.err(err)
        })
    },
    /**
     * 根据数据表名和指定查询条件查询
     */
    'GET /mysql/findBy': async (ctx, next) => {
        ctx.response.type = 'application/json';
        ctx.append('Access-Control-Allow-Origin', '*')
        let table = ctx.request.body.table
        let where = ctx.request.body.where
        await db.selectBy(table, where).then(res => {
            ctx.body = util.res(res)

        }).catch(err => {
            ctx.body = util.err(err)
        })
    },
    /**
     * 根据数据表名和id查询
     */
    'GET /mysql/findById': async (ctx, next) => {
        ctx.response.type = 'application/json';
        ctx.append('Access-Control-Allow-Origin', '*')
        let table = ctx.request.query.table
        let id = ctx.request.query.id
        let sql = `select * from ${table} where id='${id}'`
        await db.selectAll(sql).then(res => {
            ctx.body = util.res(res)

        }).catch(err => {
            ctx.body = util.err(err)
        })
    },

    /**
     * 添加数据
     */
    'POST /mysql/add': async (ctx, next) => {
        // ctx.response.type = 'application/json'; 
        // ctx.res.header('Access-Control-Allow-Origin', '*');

        if (ctx.req.method == 'POST') {
            let data = await util_http.getPOSTRes(ctx.req)
            data = JSON.parse(data)
            let table = data.table
            let params = data.params
            await db.insertData(table, params).then(res => {
                ctx.body = util.res(res)
            }).catch(err => {
                ctx.body = util.err(err)
            })
        } else {
            ctx.body = util.err('请求错误')
        }


    },
    /**
     * 更新数据
     */
    'PUT /mysql/update': async (ctx, next) => {
        if (ctx.req.method == 'PUT') {
            let data = await util_http.getPOSTRes(ctx.req)
            data = JSON.parse(data)
            let table = data.table
            let sets = data.sets
            let where = data.where
           // console.log('sql', table, sets, where)
            await db.updateData(table, sets, where).then(res => {
                ctx.body = util.res(res)
            }).catch(err => {
                ctx.body = util.err(err)
            })
        } else {
            ctx.body = util.err('请求错误')
        }
    },
    // /**
    //  * 更新数据
    //  */
    // 'PATCH /mysql/patch': async (ctx, next) => {
    //     // ctx.response.type = 'application/json';
    //     console.log('patch init')
    //     ctx.body = '2222'
    //     //ctx.body=util.res('123')
    //     // console.log('request',ctx.request)
    //     // let table = ctx.request.body.table
    //     // console.log('table',table)
    //     // let sets = ctx.request.body.sets
    //     // let where = ctx.request.body.where
    //     // await db.updateData(table, sets, where).then(res => {
    //     //     ctx.body = util.res(res)
    //     // }).catch(err => {
    //     //     ctx.body = util.err(err)
    //     // })
    // },
    /**
     * 删除数据
     */
    'DELETE /mysql/delete': async (ctx, next) => {  
        let table = ctx.request.body.table
        let where = ctx.request.body.where
        await db.deleteData(table, where).then(res => {
            ctx.body = util.res(res)
        }).catch(err => {
            ctx.body = util.err(err)
        })
    },
    /**
     * 根据数据表名和id删除数据
     */
    'DELETE /mysql/deleteById': async (ctx, next) => {
        ctx.response.type = 'application/json';
        ctx.append('Access-Control-Allow-Origin', '*')
        let table = ctx.request.query.table
        let id = ctx.request.query.id
        let where = {
            id: id
        }
        await db.deleteData(table, where).then(res => {
            ctx.body = util.res(res)
        }).catch(err => {
            ctx.body = util.err(err)
        })
    }
};
mysql 数据库操作

 

git地址:https://github.com/wuyongxian20/node-api.git

更多详细参考下篇node.js接口调用示例

 

posted on 2019-10-26 16:37  eye_like  阅读(1152)  评论(0编辑  收藏  举报