node.js数据库操作
时间:2021-07-01 10:21:17
帮助过:19人阅读
= require(‘http‘
);
const mysql = require(‘mysql‘
);
const url = require(‘url‘
);
const fs = require(‘fs‘
);
//1.连接到数据库
let db =
mysql.createConnection({
host:‘localhost‘
,
user: ‘root‘
,
password:‘‘
,
database:‘‘
});
//连接池【解决并发问题】
/*let db = mysql.createPool({
connerctionLimit: 10,//默认就是10
host:‘localhost‘,
user: ‘root‘,
password:‘‘,
database:‘‘
});*/
//查询
db.query(‘SELECT * FORM user_Table‘,(err,data)=>
{
if(err){
console.log(‘错了‘
);
}else{
console.log(data);
}
});
//2.配合http
http.createServer((req,res)=>
{
const {pathname,query} = url.parse(req.url,
true);
if(pathname === ‘/reg‘
){
//参数是否正确
let {username,password} =
query;
if(!username || !
password) {
res.write(‘用户和密码不能为空‘
);
res.end();
}else if(username.length>32
){
res.write(‘用户名不能大于32位‘
);
res.end();
}else if(password.length>32
){
res.write(‘密码不能大于32位‘
);
res.end();
}else{
db.query(`SELECT ID FROM user_table WHERE username=‘${username}‘`,(err,data)=>
{
if(err){
res.write(‘数据库有错‘
);
res.end();
}else if(data.length>0
){
res.write(‘用户名已存在‘
);
res.end();
}else{
db.query(`SELECT INFO user_table (username,password) VALUES(‘${username}‘,‘${password}‘)`,err=>
{
if(err){
res.write(‘数据库有错‘
);
res.end();
}else {
res.write(‘注册成功‘
);
res.end();
}
})
}
})
}
//检查用户名是否存在
}else if(pathname === ‘/login‘
){
}else{
fs.readFile(‘www‘+pathname,(err,buffer)=>
{
if(err){
res.writeHeader(404
);
res.write(‘no found‘
);
}else{
res.write(buffer);
}
res.end();
})
}
})
3.异步模块(co-
mysql)
const co = require(‘co-mysql‘
);
let conn =
mysql.createPool({
host:‘localhost‘
,
user: ‘root‘
,
password:‘‘
,
database:‘‘
});
let db =
co(conn);
http.createServer(async (req,res)=>
{
const {pathname,query} = url.parse(req.url,
true);
if(pathname === ‘/reg‘
){
//参数是否正确
let {username,password} =
query;
if(!username || !
password) {
res.write(‘用户和密码不能为空‘
);
res.end();
}else if(username.length>32
){
res.write(‘用户名不能大于32位‘
);
res.end();
}else if(password.length>32
){
res.write(‘密码不能大于32位‘
);
res.end();
}else{
try{
let data = await db.query(`SELECT ID FROM user_table WHERE username=‘${username}‘
`);
if(data.length>0
){
res.write(‘用户名已存在‘
);
}else{
await db.query(`SELECT INFO user_table (username,password) VALUES(‘${username}‘,‘${password}‘
)`);
res.write(‘注册成功‘
);
}
}catch(err){
res.write(‘数据库有错‘
);
}
res.end();
}
//检查用户名是否存在
}else if(pathname === ‘/login‘
){
}else{
fs.readFile(‘www‘+pathname,(err,buffer)=>
{
if(err){
res.writeHeader(404
);
res.write(‘no found‘
);
}else{
res.write(buffer);
}
res.end();
})
}
})
node.js数据库操作
标签:root HERE server sync 数据库操作 catch login epo table