node.jsデータベース操作
10140 ワード
node mysql
const http = 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();
})
}
})
転載先:https://www.cnblogs.com/jjq-exchange/p/11562997.html