2021-04-13 node操作数据库

const express = require('express')
const app = express();
const querystring = require('querystring');


// 导入 myspl 
const mysql = require('mysql')


var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'mysql_001'
});


//   调用查询语句
// connection.query('要执行的语句')
var sqlStr = 'select * from users'
connection.query(sqlStr, (err, result) => {
    if (err) return console.log('获取数据失败' + err.message);
    console.log(result);
})


// 新增 
const user={uname:'新啊',age:12,gender:'男'};
const sqlStr2='insert into users set ?'

connection.query(sqlStr2,user, (err, result) => {
    if (err) return console.log('获取数据失败' + err.message);
    console.log(result);
})




app.use((req, res, next) => {
    let dataStr = ''
    req.on('data', chunk => {
        dataStr += chunk
    })

    // 只有req 触发了end 事件 请求结束  中间件一定要合理的使用next
    req.on('end', () => {
        console.log(dataStr);
        const obj = querystring.parse(dataStr);
        console.log(obj);
        req.body = obj
        next()
    })
})

app.get('/', (req, res) => {
    res.sendFile('./views/index.html', { root: __dirname })
})
app.post('/postdata', (req, res) => {
    console.log(req.body);
    res.send(req.body)
})
app.listen(3001, () => {
    console.log('app running at http://127.0.0.1:3001');
})
// 修改
const user = { id: 2, uname: '修改的', age: 19, gender: '男' };
const sqlStr3 = 'update users set ? where id=?'

connection.query(sqlStr3, [user,user.id], (err, result) => {
    if (err) return console.log('修改数据失败' + err.message);
    console.log(result);
})

// 删除
const user = { id: 2, uname: '修改的', age: 19, gender: '男' };
const sqlStr4 = 'delete from users where id=?'

connection.query(sqlStr4,2, (err, result) => {
    if (err) return console.log('删除数据失败' + err.message);
    console.log(result);
})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值