连接数据库写一个真正的接口

1.封装sql模块

// 1. 加载mysql
const mysql = require('mysql');
// 2. 创建连接对象
const connection =  mysql.createConnection({
    // 对象的属性名字不能改变
    host: 'localhost', 
    port: 3306,       //数据库端口
    user: 'root',     //用户
    password: 'root', //密码
    database: 'tt'    //自己创建的数据库名字
});
// 3. 连接到MySQL服务器
connection.connect((err) => {
  // 如果有错误对象,表示连接失败
  if (err) return console.log('数据库连接失败')
  // 没有错误对象提示连接成功
  console.log('mysql数据库连接成功')
});
module.exports = connection

2.创建数据库student,新建两个字段分别为name类型(varchar),age类型(int) 

 

const express = require('express')
const app = express()
const connection = require('./sql')
app.use(express.urlencoded())   //中间件,生成req.body保存请求体
app.post('/api/student', (req, res) => {
    //接收到普通键值对的参数
    const {
        name,
        age
    } = req.body
    //添加到数据库中
    const sql = `insert into student (name,age) values ('${name}',${age})`//注意!
    connection.query(sql, (err, data) => {
        if (err) {
            console.log(err);
            //返回  
            res.json({
                msg: '添加失败',
                code: 0
            })
        } else {
            console.log('添加成功');
            res.json({
                msg: '添加成功',
                code: 1
            })
        }

    })

})
app.get('/api/student', (req, res) => {
    //接收到普通键值对的参数
    const sql='select * from student'
    //添加到数据库中
    connection.query(sql, (err, result) => {
        if (err) {
            console.log(err);
            //返回  
            res.json({
                msg: '查询失败',
                code: 0
            })
        } else {
            console.log('查询成功');
            res.json({
                msg: '查询成功',
                code: 1,
                data:result
            })
            console.log(result);
        }
    })
})

app.listen(3000, () => {
    console.log('---------接口服务器开始3000----------');
})

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值