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