Nodejs连接MySQL&&实现unity中的登陆注册功能

MySQL是一款常用的开源数据库产品,通常也是免费数据库的首选。查了一下NPM列表,发现Nodejs13库可以访问MySQLfelixge/node-mysql似乎是最受关注项目,我也决定尝试用一下。

要注意名字,”felixge/node-mysql””node-mysql”,安装目录

1. node-mysql介绍

felixge/node-mysql是一个纯nodejs的用javascript实现的一个MySQL客户端程序。felixge/node-mysql封装了NodejsMySQL的基本操作

项目地址:https://github.com/felixge/node-mysql

 

3. node-mysql安装

npm install mysql

 

在项目目录下新建app.js测试:

 

      1 var mysql =require(‘mysql‘);                                                           

      2 var conn = mysql.createConnection({

      3         host: ‘localhost‘,

      4         user: ‘root‘,

      5         password: ‘‘,

      6        // database:‘‘,

      7         port: 3306

      8 });

      9 conn.connect();

     10 conn.query(‘insert into`Pomelo`.`User` ( `name`, `id`, `password`) values ( "wang", " 1", "123")‘ , function(err, rows, fields) {

     11         if (err) throw err;

     12             console.log(‘The solution is: ‘, rows[0]);

     13 });

14 conn.end();

 

运行node

》》》node app.js

 

The solution is:  { id: 1,

  name: ‘wang‘,

  password: ‘123‘,

}

 

这样我们就让Nodejs连接上了MySQL

 

 

接下来就该使用具体实例来试验了,我们在unity中用NGUI制作登陆注册页面,实现客户端的登陆注册功能。

unity客户端的脚本代码:

 

using UnityEngine;
using System.Collections;

public class webloginclick : MonoBehaviour {

    public string url;
    
    public UIInput userName;
    public UIInput passWord;
    void Start () {
        url="http://127.0.0.1:1337/login";
    }
    
    
    void Update () {
        
    }
    IEnumerator OnClick(){
        WWWForm form1=new WWWForm();
        form1.AddField("username",userName.value);
        form1.AddField("password",passWord.value);
        
        WWW www1=new WWW(url,form1);
        yield return www1;
        print (www1.text);
        if(www1.text=="2"){
            Application.LoadLevel(1);
            Debug.Log("Login success");
        }else{
            Debug.Log("Login File");
        
            
        }
        
    

    }
}

 

 

客户端请求好了URL我们就需要在nodejs服务器端进行接收了,首先确保nodejs是可以连接上数据库的,我们在服务器端新建app.js  代码如下:

varpath=require(‘path‘);

varserverStatic=require(‘./servers.js‘);

var http =require(‘http‘);

varqs=require(‘querystring‘);

varurl=require(‘url‘);

var mysql =require(‘../mysqltest/node_modules/mysql‘);

//连接数据库:

function mydb(){

    var conn = mysql.createConnection({

     host: ‘127.0.0.1‘,

     user: ‘root‘,

     password: ‘‘,

     database:‘mydata‘,

     port: 3306

    });

    conn.connect();

    return conn;

}

http.createServer(function(request, response) {

    varurlpre=url.parse(request.url).pathname;//按照‘/’的方式分割字符串,取出第一段

     var resData=‘‘;//声明一个空的全局变量为空的

     console.log(urlpre);

      if(urlpre==‘/public‘){

     serverStatic.s(request,response);

     }

     if(urlpre==‘/reg‘){

        

        request.on(‘data‘,function(data){

           resData+=data;

 

        });

        request.on(‘end‘,function(){

           var conne=mydb();

           var obj=qs.parse(resData);

           varpost={name:obj.username,pssword:obj.password1};

           conne.query("INSERT INTO mytable SET?",post,function(err,result){

               response.write(‘zhuce success‘);

         

           });

           //conne.end();

        });

     }

     if(urlpre==‘/login‘){

       request.on(‘data‘,function(data){

          resData+=data;

       });

       request.on(‘end‘,function(){

          var conne=mydb();

          var obj=qs.parse(resData);

  

          varpost={name:obj.username,pssword:obj.password1};

          var Sql=conne.query(‘select * frommytable where name = ?‘,obj.username,function(err,row,result){

              console.log(row[0]);

              if(row[0]==undefined){

                      console.log(‘1‘);

                                                              response.end("1");//登陆失败

              }else{

                       console.log(‘2‘);

                                                             response.end("2");//登陆成功

              }

 

       });

      

      

   

              //conne.end();测试的时候记得启动服务

       });

    }

 

     

}).listen(1337,‘127.0.0.1‘);

 

静态服务器端的代码如下:在app.js文件中需要引入静态服务器代码:

servers.js:

 

 

 

var fs  = require(‘fs‘);

//var mime =require(‘mime‘);

var cache = {};

 

functionsend404(response) {

  response.writeHead(404, {‘Content-Type‘:‘text/plain‘});

  response.write(‘Error 404: resource notfound.‘);

  response.end();

}

 

functionsendFile(response, filePath, fileContents) {

  response.writeHead(

    200,

    //{"content-type":mime.lookup(path.basename(filePath))}

    {"content-type": ‘text/html‘}

  );

  response.end(fileContents);

}

 

functionserveStatic(request,response) {

   

     var filePath=false;

     if(request.url==‘public/‘){

     filePath=‘public/index.html‘;

     } else{

        filePath=request.url;

     }

     var absPath=‘.‘+filePath;

  

     if (cache[absPath]) {

    sendFile(response, absPath,cache[absPath]);

  } else {

    fs.exists(absPath, function(exists) {

      if (exists) {

        fs.readFile(absPath, function(err,data) {

          if (err) {

            send404(response);

          } else {

            cache[absPath] = data;

            sendFile(response, absPath, data);

          }

        });

      } else {

        send404(response);

      }

    });

  }

}

exports.s=serveStatic;

exports.send404=send404;

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。