引入模块
const mysql = require('mysql');
const http = require('http');
const url = require('url');
const querystring = require('querystring');
创建http服务器
let server = http.createServer((req, res) => {
if (req.url == "/favicon.ico") {
res.end("");
return
}
//如果地址包含“reg/add”则进行添加操作
if (/reg\/add/.test(req.url)) {
let {
username,
password,
phone
} = url.parse(req.url, true).query;
//创建mysql实例
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'class'
});
//连接数据库
connection.connect();
//添加数据
let sql = `insert user (username,password,phone) values('${username}','${password}','${phone}')`;
connection.query(sql, function(error, results, fields) {
//有错误则抛出
if (error) throw error;
res.end('add success');
})
//查询数据库
connection.query('SELECT * from user', function (error, results, fields) {
//有错误则抛出
if (error) throw error;
// console.log('The solution is: ', results); //查询结果
let res = [];
results.forEach(ele => {
//1.使用JSON.stringify转为合法的JSON串 2.使用JSON.parse转为可访问的js对象
res.push(JSON.parse(JSON.stringify(ele)));
})
console.log(res);
});
//断开数据库连接
connection.end();
}
}).listen('1234')
注意事项:
- 更新-update
update 表名 set key=value,key=value where 条件;
`UPDATE user SET username='admin'; `
- 删除-delete
DELETE FROM 表名 where 条件;
`DELETE from user where id = 12;` -- DELETE要大写
- 查询-select
select * from 表名
`select * from user;`
网友评论