nodeJs操作数据库都需要引入对应的数据库操作模块。
1、操作mysql数据库:
const mysql = require("mysql");
const connection = mysql.createConnection({
host: 'localhost', //地址
user: 'root', //用户名
password: '', //数据库密码
database: 'class', //数据库名
multipleStatements: true, // 允许执行多条语句
})
2、由于nodeJs里面的操作都是异步操作,所以操作数据库异步问题,所以借助promise,配合async以及await。
function fn(sql,data = []){
return new Promise((res,rej)=>{
connection.query(sql,data,(err,result)=>{
if(!err){
res(result);
}else{
rej(err);
}
})
})
}
3、开启http服务,进行数据库操作
const http = require("http");
const querystr = require("querystring")
const url = require("url");
const server = http.createServer(async (req, res) => {
var str = '';
req.on("data", (_data) => {
str = query.parse("_data");
})
res.writeHead(200, {
"content-type": "text/html;charset=utf-8"
})
// res.write(JSON.stringify({
// code:1,
// data:str,
// msg:"请求成功"
// }))
const { pathname, query } = url.parse(req.url)
var datas = {};
if (pathname != "/favicon.ico") {
switch(pathname){
case "/list":
datas = await fn("select * from users");
console.log(datas, pathname)
break;
case "/add":
var {username, password, tel, email} = querystr.parse(query)
var sql = `insert into users(Username,Password,Tel,Email) values(?,?,?,?)`;
var selects = [username, password, tel, email];
datas = await fn(sql,selects);
// console.log(datas, pathname);
break;
case "/del":
var {id} = querystr.parse(query);
datas = await fn(`delete from users where ID = ${id}`);
console.log(datas, pathname);
break;
case "/update":
var {username, password, tel, email,id} = querystr.parse(query);
var sql = "UPDATE users set Username = ?,Password = ?,Tel = ?,Email = ? where ID = ?";
var selects = [username, password, tel, email,id];
datas = await fn(sql,selects);
// console.log(datas, pathname);
break;
}
}
res.end(JSON.stringify({
code: 1,
data: datas,
msg: "请求成功"
}));
})
server.listen(10086, () => {
console.log("服务开启成功")
})
以上就是nodeJs操作mysql数据库的步骤