nodejs 链接数据库的一些代码

var http = require('http');
var mysql = require('mysql');
var querystring = require('querystring');

//链接数据库的基本的元素
var pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'psychologyapp',
    port: 3306
});

var post_data = {ret:0};
var app = http.createServer(function (request, response) {  //0
	request.setEncoding('utf-8');

  // 注册监听, 接收数据块
  var postData = '';
  request.addListener("data", function (postDataChunk) {
      postData += postDataChunk;
  });


  // 数据接收完毕, 执行回调函数
  request.addListener("end", function () { //1 监听
  var params = querystring.parse(postData);  //解析 HEADER 
 
//通过post进来的参数,这里我们知道登录只有手机号码和密码
  var phoneReq = params['phone'];
  var passwordReq = params['password'];
  console.log("phoneReq "+phoneReq);
  console.log("passwordReq "+passwordReq);


//sql语句
  var selectSQL = 'select * from user_info';
  pool.getConnection(function (err, conn) { //2连接
      if (err) console.log("POOL ==> " + err);
     
      var success = 0;
      var data = "";


      conn.query(selectSQL,function(err,rows){//3查询
          if (err) 
            console.log(err);
          
          console.log(rows);
          
          // console.log('+++++++++++');
          for(var i in rows){
          
          var phone = new String(rows[i].phone);
          // console.log('phone is :'+phone);
           
            if(phoneReq == phone){
              console.log('it has the phone number is :'+phone);
               data = {ret:0};
               success = '1';
            }
           // console.log('+++++++++++');
          }


       console.log('success '+success);
        if (success == 1) {
          data = {ret:0};
        }else{
          data = {ret:1};
        }


        conn.release();


        response.writeHead(200, {'Content-Type': 'application/json'});
        response.write(JSON.stringify(data));
        response.end();
         }); //3 查询
        }); //2 连接
      });  //1 监听
});


app.listen(9000);
console.log('Server running at http://127.0.0.1:9000/login');


运行,然后在app的登录界面访问,就可以在终端的启动页面可以看到相应的查询数据和相应的东东是否匹配。

nodejs 链接数据库的一些代码_第1张图片

参考链接:

node-mysql 的结果:

https://www.mgenware.com/blog/?p=2846 


mysql-workbench 的使用

http://blog.csdn.net/u011719449/article/details/12521437


http://blog.fens.me/nodejs-mysql-intro/
nodejs 链接msyql  以及nodejs-mysql的安装

(直接到github上查找到这个库,然后直接下载,通过npm)

eg:npm install mysql@版本




你可能感兴趣的:(mysql,ios开发,javaScript)