mysql 查询法来作为Sque的辅助

mysqlApi.js

let mysql = require('mysql');

let db_config={
    //Options
   host:'10.22.71.92',
   port:'3306',
   user:'root',
   password:'wang',
   database:'wang'
}



const pool = mysql.createPool(db_config)
let query = function( sql, values ) { 
    return new Promise(( resolve, reject )=> { 
         pool.getConnection(function(err, connection) { 
            if(err) { 
                reject( err )
            }
            else {
                connection.query(sql, values, ( err, rows) => { 
                    if ( err ) {
                        reject( err ) 
                    }
                    else {
                        resolve( rows ) 
                    } 
                    connection.release() 
                }) 
            } 
        }) 
    }) 
} 

exports.query = query

用的时候

const mysqlApi = require('./model/mysqlApi')
const query = mysqlApi.query

router.post('/comment', async (ctx, next) => {
    let row =  ctx.request.body;
    console.log(row)
    let {articleid,content} = row

    let sqlStr = `select  * from comment where article_id = ${articleid} order by id asc LIMIT 1`
    console.log(sqlStr)
    let ret =   await query( sqlStr )

    console.log(ret)
    console.log(ret.length)
    let art ={}

    let comment_no = 1
    if(ret.length > 0){
        comment_no = ret[0].comment_no+1
    }
        let tt = {
            article_id:articleid,
            content:content,
            comment_no:comment_no
        }
        art = await Comment.create(tt)
    
    ctx.body = art
})

router.get("/comment",async ctx => {
    let request = ctx.request;
    let req_query = request.query;
    const id = req_query.id;
    let sqlStr = `select  * from comment where article_id = ${id} order by id asc `
    console.log(sqlStr)
    let ret =   await query( sqlStr )

 
    ctx.body = ret
})

 

posted @ 2020-10-10 14:19  cnchengv  阅读(141)  评论(0编辑  收藏  举报