Nodejs连接数据库

var mysql = require('mysql');

var connection = mysql.createConnection({

host:'localhost',

user:'root',

password:'',

database:'mtc',

port:'3306'

});


//链接

connection.connect(function(err){

if(err){

console.log('[query]-:'+err);

return;

}

console.log('[connection connect] successed');

});


//插入

// var insertSql = "INSERT INTO mtc_users(user_name,user_pass,create_time) VALUES(?,?,?)";

// var params = ['lisi','lisi222','45678'];

// connection.query(insertSql,params,function(err,rs){

//  if (err) {

//  console.log('INSERT ERR:'+err.message);

//  return;

//  }


//  console.log('INSERT SUCCESS');

// });


//查询

// // var selectSql = "SELECT * FROM mtc_users WHERE user_id = ? ";

// var selectSql = "SELECT * FROM mtc_users WHERE 1 ";

// // var selectParams = ['1'];

// // connection.query(selectSql,selectParams,function(err,rs,fields){

// connection.query(selectSql,function(err,rs,fields){

//  if (err) {

//  console.log('query'+err);

//  return;

//  }

//  // console.log('The solution is ',rs[0].user_name);

//  // for(var i = 0;i<rs.length;i++){

//  //  console.log('The solution is ',rs[i].user_name);

//  // }

//  console.log(fields);

// });


//修改

// var updateSql = "UPDATE mtc_users SET user_pass = ? WHERE user_id = ? ";

// var updateParams = ['147','1'];

// connection.query(updateSql,updateParams,function(err,rs){

//  if (err) {

//  console.log(err);

//  return;

//  }


//  console.log(rs);

// });


//删除

var deleteSql = "DELETE FROM mtc_users WHERE user_id = ? ";

var deleteParams = ['2'];

connection.query(deleteSql,deleteParams,function(err,rs){

if (err) {

console.log(err);

return;

}

console.log(rs);

});


//关闭

connection.end(function(err){

if (err) {

console.log(err.toString());

return;

}

console.log('[connection end] successed');

});

本文转自  素颜猪  51CTO博客,原文链接:http://blog.51cto.com/suyanzhu/1891728

上一篇:「比较含退格的字符串」python之leetcode刷题|008


下一篇:Nodejs使用连接池连接数据库