nidejs的数据库和json文件操作

var mysql = require('mysql');

var fs = require("fs");
var con = mysql.createConnection({
host:'127.0.0.1',
user:'root',
password:'root',
database:'test'

});

exports.looksql =function(){

	con.connect();
	var sql ='select * from user';
	con.query(sql,function(err,rr){
		 console.log(1111);
		console.log(JSON.stringify(rr));

	
	
	
	});

	
	console.log('end');
	con.end();
}
exports.addsql=function(){

// con.connect();
// var  addSql = 'INSERT INTO user(name) VALUES(?)';
// var  addSqlParams = ['菜鸟工具'];
// //增
// con.query(addSql,addSqlParams,function (err, red) {
        // if(err){
         // console.log('[INSERT ERROR] - ',err.message);
         // return;
        // }        
 
       // console.log('--------------------------INSERT----------------------------');
       // //console.log('INSERT ID:',result.insertId);        
       // console.log('INSERT ID:',red);        
       // console.log('-----------------------------------------------------------------\n\n');  
// });

con.connect();
var sql ='insert into user(name) values(?)';
var valc =['jinjin'];
	con.query(sql,valc,function(err,red){
	console.log(red);
		
	
	
	
	
});
con.end();


}
exports.insql=function(){
	con.connect();
	var sql = 'update user set name=? where id=3';
	var da =['jinjin11'];
	con.query(sql,da,function(err,red){
		console.log(red);
		
		
		
	});
	
	
}
exports.delsql=function(){
	
con.connect();
var sql ='delete from user where id=2';	
con.query(sql,function(err,red){
	console.log(red.affectedRows);
	
	
});
con.end();	
}

exports.addjson=function(name,da){
	var user = da;
	 fs.readFile("in.json",'utf8',function(err,data){
		if(err){
			return err;
		}
		var data = JSON.parse(data);
		data[name] = user;
		fs.writeFile("in.json",JSON.stringify(data), function (err) {
			if(err){
				return console.error(err);
			}
			console.log("数据写入成功!");
		});
	 });
		
		
	}
exports.ajson=function(name,da){
	var user= da;
	fs.readFile("in.json",function(err,data){
		if(err){
			
			return err;
		}
		var data =JSON.parse(data);
		data[name] = user;
		fs.writeFile("in.json",JSON.stringify(data),function(err){
			
			if(err){
				
				return err;
			}
			console.log("caozuochenggong");
		});
		
	});
	
	
}
	
	

exports.lookjson=function(name){
	fs.readFile("./in.json",'utf8',function(drr,data){
		data = JSON.parse(data);
		var user = data[name]
		console.log(user);
		
	});
	
}
exports.deljson = function(name){
	
	 fs.readFile("./in.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       delete data[name];
       fs.writeFile("in.json",JSON.stringify(data),function(err){
		   if(err){
			   return err
			   
		   }
		   console.log("删除成功");
	   });
       console.log( data );
	 });
}


评论

刷新

友情链接