资源描述:
《node.js连接mysql及相关操作》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
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数据库exports.ready=function(callback){//this.state="disconnected";if(connection.state!='disconnected'){returninvoke(callback,{"code":0,"message":"alreadyconnectmysql"});}//连接mysql数据库connection.connect(function(error){if(error){returninvoke(callbac
6、k,{"code":1,"message":"connecterror:"+error.message});}returninvoke(callback,{"code":0,"message":"ConnecttoMysqlOK!"});});}//插入数据exports.insert=function(callback){varsql='INSERTINTOt_testSETid=?,name=?,fee=?,address=?';varvalues=[sid++,'李四'+sid,888,'
7、上海市浦东新区1800号'];//插入数据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);});}//查询数据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