資源描述:
《node.js連接mysql及相關(guān)操作》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫。
1、File:mysqlDAO.js---------------------------------------------------------------------------------------------------------------------------------/***CreatedbyAdministratoron14-12-30.*TestMysqlDBOperation*/varsys=require('sys');varmysql=require('mysql
2、');varconnection=mysql.createConnection({host:'localhost',user:'root',password:'root',port:'3306',database:'test'});varsid=100;functioninvoke(callback,data){if(callback==null
3、
4、typeofcallback=="function"){console.log(data);return;}callback(data);}//連接
5、Mysql數(shù)據(jù)庫exports.ready=function(callback){//this.state="disconnected";if(connection.state!='disconnected'){returninvoke(callback,{"code":0,"message":"alreadyconnectmysql"});}//連接mysql數(shù)據(jù)庫connection.connect(function(error){if(error){returninvoke(callbac
6、k,{"code":1,"message":"connecterror:"+error.message});}returninvoke(callback,{"code":0,"message":"ConnecttoMysqlOK!"});});}//插入數(shù)據(jù)exports.insert=function(callback){varsql='INSERTINTOt_testSETid=?,name=?,fee=?,address=?';varvalues=[sid++,'李四'+sid,888,'
7、上海市浦東新區(qū)1800號(hào)'];//插入數(shù)據(jù)connection.query(sql,values,function(error,results){if(error){returninvoke(callback,{"code":1,"message":'ClientReadyError:'+error.message});}returninvoke(callback,{"code":0,"message":'Idinserted:'+results.insertId});//console.log
8、('Inserted:'+results.affectedRows+'row.');//console.log('Idinserted:'+results.insertId);});}//查詢數(shù)據(jù)exports.getData=function(callback){connection.query('SELECT*FROMt_test',function(error,results){if(error){invoke(callback,{"code":1,"message":'GetDataEr
9、ror:'+error.message});return;}if(results.length>0){vardata="";for(vari=0;i10、turn;});};File:mytest.js---------------------------------------------------------------------------------------------------------------------------------"usestrict";varconfig=require('../config');varmysql=require('../dao/mysqlDao');exports.hello=func