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----------');
})