zoukankan      html  css  js  c++  java
  • node.js如何读取MySQL数据

    先安装mysql模块。

    node.js默认安装时,模块文件放在 /usr/local/lib/node_modules 这个目录下,为了便宜管理,模块还是统一安装到这里好。

    $ cd /usr/local/lib         
    $ npm install mysql         
    

    程序文件mysql.js

    var Client = require('/usr/local/lib/node_modules/mysql').Client;
    var client = new Client();
    
    client.user = 'root';
    client.password = '';
    
    console.log('Connecting to MySQL...');
    
    client.query('USE tiny_shop');     //如果MySQL中没有库表,赶紧建。
    
    http = require("http");
    
    var server = http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
    
        client.query('SELECT * FROM tags', function selectCb(err, results, fields) {  
            if (err) {  
                throw err;  
            }  
    
            var data = '';
            for (var i=0; i<results.length; i++) {          
                var firstResult = results[i];
                data += 'id: ' + firstResult['id']+'tag: ' + firstResult['tag']; 
            } 
    
            response.write(data); 
            response.end();
        });
    });
    
    server.listen(8080);
    
    var sys = require("util");
    sys.puts("Server running at http://localhost:8080/"); 
    

    运行

    $ node mysql.js
    

    在浏览器里,输入 http://localhost:8080 ,就能显示数据库里的数据了。

  • 相关阅读:
    IO多路复用--epoll(待学习)
    网络信息检索
    TCP协议的客户端与服务器的通信过程
    UDP网络编程
    HDU_oj_2017 字符串统计
    HDU_oj_2016 数据的交换输出
    HDU_oj_2015 偶数求和
    HDU_oj_2014 评委会打分
    HDU_oj_2013 蟠桃记
    HDU_oj_2012 素数判定
  • 原文地址:https://www.cnblogs.com/saryli/p/6917931.html
Copyright © 2011-2022 走看看